0

私はこの正規表現を持っています:

<?PHP
$test = 'this is a #test';
$regex = "#(\#.)#i";
$test = preg_replace($regex, '<strong>$1</strong>', $test);
echo $test;
?>

#の後の単語を強くしたいのですが、#tだけが強いのですが、誰か提案がありますか?どうもありがとう

4

4 に答える 4

3

私の提案はこのようなものになるでしょう-

$regex = "/#(\w+)/i";

The \w means any word character. I'm also using the + quantifier which indicates that we must match at least one word character after the hash sign. I'm assuming we don't want just the hash sign to be <strong> I also removed the hash sign (#) from the capture group as I'm not too sure you want that character to remain after you wrap it with <strong>.

One final note I'll leave you with is that if you find yourself using your delimiter within your regular expression, you might want to consider changing it to something that you wouldn't use normally. In your case you had to escape the hash sign but in my example, I've changed the delimiter to slashes. It makes it a little bit easier to read as well :)

于 2012-11-10T01:05:52.540 に答える
2

+1つ以上の数値リテラルに一致させるために使用します。の後にリテラルの出現*を含める場合は、を使用します。0#

   $regex = "#(\#.+)#i";

詳細については、 PHPRegexRepetitionのドキュメントを参照してください。

于 2012-11-10T00:58:22.867 に答える
0

これを試して:

<?PHP
$test = 'this is a #test';
$regex = "#(\#.*)#i";
$test = preg_replace($regex, '<strong>$1</strong>', $test);
echo $test;
?>

問題は 。単一の文字としてのみ一致します。

于 2012-11-10T00:58:34.487 に答える
-1

保存するシンボルの量を設定する必要があります。

$regex = "#(\#.{4})#i";
于 2012-11-10T00:57:33.850 に答える