preg_replace insade paragprah添加锚链接

时间:2017-04-07 10:29:40

标签: php preg-replace

我想将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>

1 个答案:

答案 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