Jump to content

code problam str_relace and others....


redarrow

Recommended Posts

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

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;
}
}
  }
?>

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

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.