0

这是我的代码

    $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;

输出

据《印度时报》报道,&[h]#8220[/h] Telan#gana Rashtra Samiti 酋长 K Chandrasekhar [h]#Rao[/h] 看到了 [h]#sinister[/h ] 反对特伦甘纳语形成的抗议背后的动机

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

4

1 回答 1

2

尝试使用积极的lookbehind,因为在 hash 之前总是有一个单词边界#

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

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

您可以在 a 中使用它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);
于 2013-10-08T07:22:28.807 回答