replace after preg_match or preg_match_all

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gd77
Forum Newbie
Posts: 20
Joined: Sat Feb 26, 2011 6:11 pm

replace after preg_match or preg_match_all

Post 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.
User avatar
gd77
Forum Newbie
Posts: 20
Joined: Sat Feb 26, 2011 6:11 pm

Re: replace after preg_match or preg_match_all

Post 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 ""

}
User avatar
gd77
Forum Newbie
Posts: 20
Joined: Sat Feb 26, 2011 6:11 pm

Re: replace after preg_match or preg_match_all

Post 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>.
Post Reply