围绕某些单词包裹标签

cpd*_*pdt 3 php regex tags

我有一系列的单词,像这样:

array("the", "over", "hen");
Run Code Online (Sandbox Code Playgroud)

我也有这样的字符串:

"The quick brown fox jumps over the lazy hen"
Run Code Online (Sandbox Code Playgroud)

我想换一个标签(strong)周围的所有的阵列中的字出现,但保留的情况下是正确的.

例如,使用前一个字符串,它最终会像

<strong>The</strong> quick brown fox jumps <strong>over</strong the lazy <strong>hen</strong>
Run Code Online (Sandbox Code Playgroud)

但是,如果我有这句话:

"Hen #2 and ThE oveR reactive cow"
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

<strong>Hen</strong> #2 and <strong>ThE</strong> <strong>oveR</strong> reactive cow
Run Code Online (Sandbox Code Playgroud)

我猜这个答案会使用正则表达式,但我不是很擅长......

Bor*_*ora 6

试试以下:

$string = 'Then quick brown fox jumps over the lazy hen';
$keys = array('the', 'over', 'hen');

$patterns = array();
foreach($keys as $key)
    $patterns[] = '/\b('.$key.')\b/i';

echo preg_replace($patterns, '<strong>$0</strong>', $string);
Run Code Online (Sandbox Code Playgroud)