php正则表达式需要特殊字符

时间:2013-10-08 07:19:17

标签: php regex preg-replace

这里是我的代码

    $string="According to a report on the Times of In#dia, &#8220 Telan#gana Rashtra Samiti chief K Chandrasekhar #Rao has seen a #sinister motive behind the protests against the formation of Telangana";
preg_match_all('/(?!\b)(#\w+\b)/' ,$string, $matches);

foreach($matches[1] as $match){
$string = str_replace("$match","[h]".$match."[/h]",$string);

}

echo $string;

输出

  

根据关于#dia的时代报道,& [h]#8220 [/ h] Telan#gana   Rashtra Samiti首席K Chandrasekhar [h] #Rao [/ h]见过一个   [h] #sinister [/ h]抗议形成背后的动机   特兰伽纳

我想只替换以#开头的字符串,但它也将&#8220替换为&[h]#8220[/h]。请帮助我。

1 个答案:

答案 0 :(得分:2)

尝试使用正面的lookbehind,因为在哈希#之前总是有一个单词边界:

/(?<=\s|^)(#\w+\b)/

这确保在散列词之前有一个空格或字符串的开头。

您可以在preg_replace

中使用此功能
$string="According to a report on the Times of In#dia, &#8220 Telan#gana Rashtra Samiti chief K Chandrasekhar #Rao has seen a #sinister motive behind the protests against the formation of Telangana";
$result = preg_replace('/(?<=\s|^)(#\w+\b)/', "[h]$1[/h]", $string);