PHP preg_replace()问题

时间:2011-02-24 00:12:49

标签: php preg-replace

我想知道你是否可以提供帮助。

我有一句话:

$desc = preg_replace("/#\d{1,3}%/", "<b>$0</b>", $desc);

$ desc是推文。我希望用百分比识别哈希标签。如:

#100% or #25% or #1%

但是字符串没有匹配或替换。如果你能提供帮助,我们将不胜感激。

示例:

$desc = "testing #ugp 123 fb #75% #1% #100%. (Twitter@Feb 23, 2011 6:06 PM)";
$desc = preg_replace("/#\d{1,3}%/", "<b>$0</b>", $desc);
echo $desc;

预期输出将有3个匹配的标签包装在标签中,但输出不会改变原来的

干杯

2 个答案:

答案 0 :(得分:1)

适合我:

$desc = "testing #ugp 123 fb #75% #1% #100%. (Twitter@Feb 23, 2011 6:06 PM)";
$desc = preg_replace("/#\d{1,3}%/", "<b>$0</b>", $desc);
echo $desc; //testing #ugp 123 fb <b>#75%</b> <b>#1%</b> <b>#100%</b>. (Twitter@Feb 23, 2011 6:06 PM)

答案 1 :(得分:0)

你需要做两件事:

  1. 在要捕获的组周围放置括号
  2. 将$ 0更改为$ 1($ 0匹配整个正则表达式)

    preg_replace("/#(\d{1,3}%)/", "<b>$1</b>", $desc);