php - Merging preg_match_all and preg_replace -


i have code running finds out hashtags in string , turns them links. have done using preg_match_all shown below:

if(preg_match_all('/(#[a-z_]\w+)/', $postlong, $arrhashtags) > 0){ foreach ($arrhashtags[1] $strhashtag) {   $long = str_replace($strhashtag, '<a href="#" class="hashlinks">'.$strhashtag.'</a>', $postlong);      }    } 

also, search script, need bold searched keywords in result string. similar below code using preg_replace:

$string = "this description search demo"; $searchingfor = "/" . $searchquery . "/i"; $replacepattern = "<b>$0<\/b>"; preg_replace($searchingfor, $replacepattern, $string); 

the problem having both have work , should thrown combined result. 1 way can think of run resultant string preg_match_all preg_replace code if tags , searched string same? second block bold tag not desired.

update code i'm running based on answer given below still doesn't work

if(preg_match_all('/(#[a-z_]\w+)/', $postlong, $arrhashtags) > 0){ foreach ($arrhashtags[1] $strhashtag) {   $postlong = str_replace($strhashtag, '<a href="#" class="hashlinks">'.$strhashtag.'</a>', $postlong);      }    } 

and after this, run this

 $searchingfor = "/\b.?(?<!#)" . $keystring . "\b/i";  $replacepattern = "<b>$0<\/b>";  preg_replace($searchingfor, $replacepattern, $postlong); 

just know, going inside while loop, generating list

you need modify search pattern avoid ones start '#'

$postlong = "this description search demo";  if(preg_match_all('/(#[a-z_]\w+)/', $postlong, $arrhashtags) > 0){   foreach ($arrhashtags[1] $strhashtag) {     $postlong = str_replace($strhashtag, '<a href="#" class="hashlinks">'.$strhashtag.'</a>', $postlong);   } }  #  expression finds text 0 or 1 characters in front of # , negative look-behind make sure character isn't # searchingfor = "/\b.?(?<!#)" . $searchquery . "\b/i"; $replacepattern = "<b>$0<\/b>"; preg_replace($searchingfor, $replacepattern, $postlong); 

or if don't need array of available hashes reason, use preg_replace only.

$postlong = "this description #search demo";  $patterns = array('/(#[a-z_]\w+)/', "/\b.?(?<!#)" . $searchquery . "\b/i"); $replacements = array('<a href="#" class="hashlinks">'.$0.'</a>', ' "<b>$0<\/b>'); preg_replace($patterns, $replacements, $postlong); 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -