我想将insade段落文本转换为anchore链接。
$change = array(
'google' => 'www.google.com',
'facebook' => 'www.facebook.com',
);
$text = "
<h1>Search on google for facebook</h1>
<p>Search on google for facebook</p>
";
foreach ($change as $word => $url) {
$sentence = preg_replace('@(?<=\W|^)('.$word.')(?=\W|$)@i', '<a href="'.$url.'">$1</a>', $text);
}
echo $sentence;
我想要坚决:
<h1>Search on google for facebook</h1>
<p>Search on <a href="www.google.com">google</a> for <a href="www.facebook.com">facebook</a></p>
答案 0 :(得分:0)
您可以先尝试匹配p
代码并在preg_replace_callback
匿名函数中执行所有替换:
$change = array(
'google' => 'www.google.com',
'facebook' => 'www.facebook.com',
);
$text = "
<h1>Search on google for facebook</h1>
<p>Search on google for facebook</p>
";
$sentence = preg_replace_callback('~(<p\b[^>]*>)(.*?)(</p>)~s', function($m) use ($change) {
return $m[1] . preg_replace(
array_map(function ($x) { return '@(?<=\W|^)('.preg_quote($x, "@").')(?=\W|$)@i'; }, array_keys($change)),
array_map(function ($y) { return '<a href="'. $y .'">$1</a>'; }, array_values($change)),
$m[2]). $m[3]; }
, $text);
echo $sentence;
请参阅PHP demo。