这是我的代码
$string="According to a report on the Times of In#dia, “ 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;
输出
根据In#dia的报道,&[h]#8220[/h] Telan#gana Rashtra Samiti首席执行官K Chandrasekhar [h]#Rao[/h]已经看到了一个 [h]#sinister[/h] 抗议成立的动机 特伦甘纳邦
我只想替换以 #
开头的字符串,但它也替换了“
&[h]#8220[/h]
. 请帮我解决这个问题。
尝试使用积极的回溯,因为在哈希#
之前总是有一个单词边界:
/(?<='s|^)(#'w+'b)/
这可确保在哈希单词之前有一个空格或字符串的开头。
您可以在preg_replace
中使用它:
$string="According to a report on the Times of In#dia, “ 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);