如何替换完全匹配或部分匹配的完整单词

时间:2016-12-01 12:52:51

标签: php regex preg-replace str-replace

我正在尝试使用 preg_replace str_ireplace 来围绕找到的关键字包装span类标记,但是对于str_ireplace,它会剪切一个单词,例如'wooding'一半例如:

<span class="highlight">wood</span>ing

以下是针,干草堆和所需返回的示例:

针:

wood

草堆:

wood and stuff
this doesnt contain the keyword
Wooding is what we do

我想要归还的内容:

<span class="highlight">wood</span> and stuff
this doesnt contain the keyword
<span class="highlight">Wooding</span> is what we do

这是我的preg_replace实验的链接: http://www.phpliveregex.com/p/i4m

3 个答案:

答案 0 :(得分:2)

试试这个正则表达式:\b(wood.*?)\b,它匹配以wood开头的单词,后跟任意数量的单词字符。

$intput = 'put your input here';
$result = preg_replace(/\b(wood.*?)\b/i, '<span class="highlight">\\1</span>', $input);

答案 1 :(得分:2)

怎么样:

$str = <<<EOD
wood and stuff
this doesnt contain the keyword
Wooding is what we do
EOD;
$needle = 'wood';
$str = preg_replace("/\w*$needle\w*/is", '<span class="highlight">$0</span>', $str);
echo $str,"\n";

<强>输出:

<span class="highlight">wood</span> and stuff
this doesnt contain the keyword
<span class="highlight">Wooding</span> is what we do

答案 2 :(得分:1)

您需要在结束字边界之前使用带有可选字符的正则表达式和单词边界,以确保它只是您要查找的单词。尝试:

$string = 'wood and stuff
this doesnt contain the keyword
Wooding is what we do';
echo preg_replace('/\b(wood[a-z]*)\b/i', '<span class="highlight">$1</span>', $string);

PHP演示:https://eval.in/689239
正则表达式演示:https://regex101.com/r/f9B6mL/1

对于多个术语,您可以使用非捕获组,|用于术语分离。

$string = 'wood and metal stuff
this doesnt contain the keyword
Wooding is what we do metals';
echo preg_replace('/\b((?:wood|metal)[a-z]*)\b/i', '<span class="highlight">$1</span>', $string);

演示:https://eval.in/689256