2017-04-07 106 views
0

我想將外觀段落文本轉換爲錨鏈接。preg_replace insade paragprah添加錨鏈接

$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

嘗試https://ideone.com/j9XqSd –

+0

非常感謝! – lilly321

回答

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

+0

段落中只能製作一次鏈接。如果是

在谷歌搜索facebook facebook

如果在第二段時間facebook做了2個鏈接,可以做一次嗎? – lilly321