首页 > 解决方案 > 在文本中搜索单词并替换它们

问题描述

我很难找到解决问题的方法。

我在变量中有一个这样的数组:

$myarray = Array (
[0] => Orange
[1] => Black
[2] => White
[3] => Yellow
[4] => Red
);

基本上,我需要在字符串中搜索数组的单词,并将它们替换为相同的单词,但使用链接。

例如,来自:

$string = "My content contains orange and also blue";

至:

$string = "My content contains <a href="www.domain.com/orange">orange</a> and also blue";

标签: php

解决方案


这可能最好使用preg_replace. 我们可以通过使用implode来创建一个正则表达式来创建每个单词的交替$myarray; 在组中捕获该单词,然后在替换中使用它以在其周围添加链接:

$string = "My content contains orange and also blue in a blackout";

$string = preg_replace('/\b(' . implode('|', $myarray) . ')\b/i', '<a href="www.domain.com/$1">$1</a>', $string);
echo $string;

输出:

My content contains <a href="www.domain.com/orange">orange</a> and also blue in a blackout

3v4l.org 上的演示

请注意,通过使用带有单词边界 ( \b) 的正则表达式,我们可以避免无意中将blackin替换blackout为链接。


推荐阅读