Page 1 of 1

replace after preg_match or preg_match_all

Posted: Fri May 27, 2011 4:38 am
by gd77
Hello:
I need to replace the matched string(s) after the preg_match or preg_match_all:
ex:

if(preg_match('/\b'.$words1.'\b/i', $Content)){
........
}

Thanks in advanced.

Re: replace after preg_match or preg_match_all

Posted: Fri May 27, 2011 10:12 am
by gd77
$badWords=array('wrd1','rd2','rd3');
$badWords1=array('<b>wrd1</b>','<b>rd2</b>','<b>rd3</b>');

$words = array_map('preg_quote', $badWords);
$pat = implode('|', $words);

$words1 = array_map('preg_quote', $badWords1);
$pat1 = implode('|', $words1);

$post_Content="some big text";

if(preg_match('/\b'.$pat.'\b/i', $post_Content)){

@@$post_Content= "" here I want to replace each matched word with $pat1 ""

}

Re: replace after preg_match or preg_match_all

Posted: Fri May 27, 2011 4:22 pm
by gd77
Fixed: thanks to Atli for the help:

$badWords = array('wrd1', 'rd2', 'rd3');
$words = array_map('preg_quote', $badWords);
$pat = implode('|', $words);
$post_Content = "A wrd1 with some rd3.";
$altered_content = preg_replace('/(' . $pat . ')/', '<b>$1</b>', $post_Content);

echo $altered_content;
Returns:
A <b>wrd1</b> with some <b>rd3</b>.