21,886
社区成员
发帖
与我相关
我的任务
分享
$str = "in the rooming, he got into the room, when he's ordered an inexpensive. \s";
$newrow = '\s'; // 这个应该转义
$newrow = preg_quote($newrow);
$pttn = "<span style='color:red'>$newrow</span>";
echo $str = preg_replace("/[\s\b]($newrow)\b/i",$pttn, $str);
in the rooming, he got into the room, when he's ordered an inexpensive. <span style='color:red'>\s</span>
为什么是 [\s\b] 而不是 \b 呢?因为 \ 不是单词的构成成分
不过把 \ 作为关键字也是够怪异的
$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);
我折腾了一下,这样就可以替换 \s 了。
$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);
$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);
<span style='color:red'>in</span> the rooming, he got into the room, when he's ordered an inexpensive.
\b 表示单词边界