php - preg_replace insade paragprah add anchor link -


i want convert insade paragraphs text anchore link.

$change = array(     'google' => 'www.google.com',     'facebook' => 'www.facebook.com', );  $text = "     <h1>search on google facebook</h1>     <p>search on google facebook</p> ";  foreach ($change $word => $url) {     $sentence = preg_replace('@(?<=\w|^)('.$word.')(?=\w|$)@i', '<a href="'.$url.'">$1</a>', $text); } echo $sentence; 

i want resolute:

<h1>search on google facebook</h1> <p>search on <a href="www.google.com">google</a> <a href="www.facebook.com">facebook</a></p> 

you may try match p tags first , perform replacements inside preg_replace_callback anonymous function:

$change = array(     'google' => 'www.google.com',     'facebook' => 'www.facebook.com', );  $text = "     <h1>search on google facebook</h1>     <p>search on google 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; 

see php demo.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -