这里是我的代码
$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;
输出
根据关于#dia的时代报道,& [h]#8220 [/ h] Telan#gana Rashtra Samiti首席K Chandrasekhar [h] #Rao [/ h]见过一个 [h] #sinister [/ h]抗议形成背后的动机 特兰伽纳
我想只替换以#
开头的字符串,但它也将“
替换为&[h]#8220[/h]
。请帮助我。
答案 0 :(得分:2)
尝试使用正面的lookbehind,因为在哈希#
之前总是有一个单词边界:
/(?<=\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);