redarrow Posted February 16, 2008 Share Posted February 16, 2008 only the word sister should be changed from the varable $word but it all goes xxx why please intreasting.. <?php $word="i got a sister"; $x=explode(' ',$word); foreach($x as $r){ $a=array("mum","dad","sister","brother"); if(in_array("$r",$a)){ $d=str_replace($a,"xxx",$r); echo $d; } } ?> Link to comment https://forums.phpfreaks.com/topic/91395-code-problam-str_relace-and-others/ Share on other sites More sharing options...
redarrow Posted February 16, 2008 Author Share Posted February 16, 2008 tried this aswell but stil xxx but the word only from the sentemce for sister suppose to change not the rest off the sentence.... result should be i got a xxx <?php $word=$_POST['word']; $word="i got a sister"; $x=explode(' ',$word); foreach($x as $r){ $a=array("mum","dad","sister","brother"); foreach($a as $b){ if($b==$r){ $d=str_replace($b,"xxx",$r); echo $d; } } } ?> Link to comment https://forums.phpfreaks.com/topic/91395-code-problam-str_relace-and-others/#findComment-468318 Share on other sites More sharing options...
wildteen88 Posted February 16, 2008 Share Posted February 16, 2008 Your code will output xxx because you are not saving the changes back to the original string. You seem to be confused with how foreach works. str_replace can take an array of replacement words to be replaced by a single string, Your code can be simplified to just: $words = array("mum","dad","sister","brother"); $string="i got a sister"; echo str_replace($words, 'xxx', $string); // result: i got a xxx Link to comment https://forums.phpfreaks.com/topic/91395-code-problam-str_relace-and-others/#findComment-468342 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.