php pre_replace() 高亮显示文字
希望在下面的文字当中高亮显示单词in
in the rooming, he got into the room, when he's ordered an inexpensive.
我是这样写的,但是连into,inexpensive, rooming,中的in 都高亮显示了;而且空格都没有了。
$pttn = "<span style='color:red'>$newrow</span>";
$str = preg_replace("/\s($newrow)\s/i",$pttn,$str);
如何写才能只显示in,而不会吧into,inexpensive, rooming,中的in也高亮??
[解决办法]
你这样写并没有错误,会只替换 in,只是要在 in 前面加个空格。
这样写好些
$str = "in the rooming, he got into the room, when he's ordered an inexpensive.";
$newrow = 'in';
$pttn = "<span style='color:red'>$newrow</span>";
echo $str = preg_replace("/\b($newrow)\b/i",$pttn, $str);
$str = "in the rooming, he got into the room, when he's ordered an inexpensive. \s";
$newrow = '\s'; // 这个会换效。
$pttn = "<span style='color:red'>$newrow</span>";
echo $str = preg_replace("/\b($newrow)\b/i",$pttn, $str);
$str = "\s in the rooming, he got into \s the room, when he's ordered an inexpensive. \s";
$newrow = "\s";
$newrow2 = addslashes($newrow);
$pttn = "<span style='color:red'>$newrow</span>";
//有一个细节,我也没搞明白 ,这里用 \b 失效了,先把结果输出来。
echo $str = preg_replace("/(\s+
[解决办法]
^)($newrow2)(\s+
[解决办法]
$)/i","\\1".$pttn."\\3", $str);