0

for this piece of code does anyone know why only the first $unuseful word is replaced in the string?

$unuseful = array(" is ", " the ", " for ", " and ", " with "," that ", " this "," or ", ",",";","/","?","!",".");
$aux = str_replace($unuseful, " " , $statement);

"dude cost that free the dude the the "-> dude cost free dude the

"dude cost that free the dude the the the"-> dude cost free dude the the

Thanks in advance!

  • have a look at this answer - http://stackoverflow.com/questions/9436002/str-replace-for-distinct-word – Mukesh Soni Jun 26 '12 at 08:40
  • A not-so-elegant solution would be to call the str_replace inside a loop and break until no further replacements are made. A proper solution would be to use a regex an `\b` assertions. – Salman A Jun 26 '12 at 09:17

3 Answers3

4

That's because you put leading and trailing spaces.

It replaces " the " once because " the the " has only 3 spaces, and you are looking to replace 4.

ericosg
  • 4,926
  • 4
  • 37
  • 59
2
    for($i=0;$i<count($unuseful);$i++)
    {$statement = str_replace($unuseful[$i], " " , $statement);}
$aux=$statement;
  • 1
    not the best solution. and there is a mistake, so only last unuseful thing will be removed from $statement and stored in $aux – Ziumin Jun 26 '12 at 08:37
1
<?php
$unuseful = array('/\s+is\s+/', '/\s+the\s+/', '/\s+for\s+/', '/\s+and\s+/', '/\s+with\s+/','/\s+that\s+/', '/\s+this\s+/','/\s+or\s+/', '/,/','/;/','/\//','/\?/','/\!/','/\./');

$challenge = 'dude cost that free the dude the the';
echo preg_replace($unuseful, ' ', $challenge)."\n";
?>

gives:

dude cost free dude the

user4035
  • 22,508
  • 11
  • 59
  • 94