【问题标题】:How to replace full words that are either fully or part matched如何替换完全匹配或部分匹配的完整单词
【发布时间】:2016-12-01 12:52:50
【问题描述】:

我正在尝试使用 preg_replacestr_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

【问题讨论】:

  • 你的文本已经是 html 文档了吗?
  • 没有 PHP 字符串(去除 HTML)
  • 你的意思是它还没有包含任何html标签?
  • 还有多少关键字需要替换?
  • 匹配单词第一部分的任何内容。所以返回突出显示的词可能是树林、木教堂、林地等

标签: php regex preg-replace str-replace


【解决方案1】:

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

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

【讨论】:

  • 如果你在 "wood" 之前有一些东西怎么办?对于前“asdwoodasd”?这是行不通的。
  • 我只想匹配关键字后面的文字,所以这可能对我有用
【解决方案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

【讨论】:

    【解决方案3】:

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

    $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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多