<? $text="this is class"; $text = str_ireplace("ass", "a**", $text); echo $text; ?> PHP: Output: this is cla** The above code replace class as cla** But i want to replace only exact word ass. I need the output should be: this is class.
$text="this is an ass way class, but as ass classes go it should work"; $text = preg_replace('#\bass\b#', 'a**', $text); echo $text; PHP:
Thanks, but the scenario is: $text="this is an ass way class, but as dog hotdog classes go it should work"; $badword=array('ass','dog'); $replace_with=array('a**','d**'); $text = preg_replace('#\bass\b#', 'a**', $text); echo $text; how to pass array in this line $text = preg_replace('#\bass\b#', 'a**', $text);
$text="this is an ass way class, but as dog hotdog classes go it should work"; $badword=array('ass' => 'a**','dog' => 'd**'); foreach($badword as $key=>$value) { $text = preg_replace('#\b'.$key.'\b#',$value, $text); } echo $text; PHP:
<? $text="this is class"; $text = str_ireplace(" ass ", " a** ", $text); echo $text; ?> Code (markup):
Nice, I done that but the code was lengthy you given the simplest one but there should one change <? $text="this is class"; $text = str_ireplace("ass ", "a** ", $text); echo $text; ?> Replace left whitespace other wise first word will not match
<? $badwords = array("ass","a$$","a55","Ass","ASS","A$$","A$$"); $text="this is an ass way class, but as dog hotdog classes go it should work"; $clean = ReplaceBadWords($text,$badwords,"a**); echo $clean; function ReplaceBadWords($str, $bad_words, $replace_str){ if (!is_array($bad_words)){ $bad_words = explode(',', $bad_words); } for ($x=0; $x < count($bad_words); $x++){ $fix = isset($bad_words[$x]) ? $bad_words[$x] : ''; $_replace_str = $replace_str; if (strlen($replace_str)==1){ $_replace_str = str_pad($_replace_str, strlen($fix), $replace_str); } $str = preg_replace('/'.$fix.'/i', $_replace_str, $str); } return $str; } ?> Code (markup): You could also modify this function to use key->value badword->replacement as tvoodoo shows in his code. To be able to handle a wider variety of bad words