$str = "A string containing the word así which should be changed to color purple";
$prac[] = "/\basí\b/i";
$prac2[] = "<span class='readword' style='color:purple'>\$0 </span>";
$str= preg_replace($prac,$prac2,$str);
echo $str;
它没有改变.但是,如果我有一个单词没有结束或以重音字符开头,它就会改变.例如:
$str = "A string containing another word which should be changed to color
purple";
$prac[] = "/\banother word\b/i";
$prac2[] = "<span class='readword' style='color:purple'>\$0 </span>";
$str= preg_replace($prac,$prac2,$str);
echo $str;
?>
如果重音位于单词的中间,它也总是有效.我还测试了数组本身和preg_replace本身的单词.使用数组或preg_replace的单词似乎没有问题.只有当我在preg_replace中使用数组作为参数时.
请帮忙,无论如何都找不到任何相关信息.
谢谢
解决方法:
使用unicode标志:
$str = "A string containing the word así which should be changed to color purple";
$prac[] = "/\basí\b/iu";
# here __^
$prac2[] = "<span class='readword' style='color:purple'>\$0 </span>";
$str= preg_replace($prac,$prac2,$str);
echo $str;
给出示例的结果:
A string containing the word <span class='readword' style='color:purple'>así </span> which should be changed to color purple