1

I have a very simple code which replaces specific values in a string and then explodes it.

But i need to do a count on the string after exploding, Here is my example

$exclude=array();
$exclude[0]="with";
$exclude[1]="on";

$search_string="Boy with a t-shirt walking on the road";
echo str_word_count($search_string);  

//the str_replace is suppose to remove the word "with" and "on" from string
// count search string before explode

$sch2 = str_replace($exclude,"", trim($search_string));
$sch=explode(" ",trim($sch2));
echo count($sch);  


//count search string after explode

//The result of the second count after exploding is suppose to be 6 and NOT 8

But when i count the $sch string after exploding, it gives me 8

It seems like there is something am doing wrong, any help will be appreciated. thanks

1
  • 1
    try doing var_dump($sch); - perhaps $sch doesn't contain what you think it does? Commented Mar 7, 2014 at 21:19

1 Answer 1

3

If you replace 'with' with nothing, then you still got two spaces. So the split will still return 8 items, one of which is an empty string where the word 'with' used to be.

To solve this, you might replace 'with ' (including space`, so you actually replace one of the two spaces as well. But I don't know if that would work in your actual production code, of course.

You could also use [array_filter][1] to filter out the empty value, like this:

$sch2 = str_replace($exclude,"", trim($search_string));
$sch = explode(" ",trim($sch2));
$sch = array_filter($sch);
echo count($sch);  

Or even:

// To prevent 'false positives' due to PHP's default weak comparison.
$sch = array_filter($sch, function($a){return $a !== '';});
Sign up to request clarification or add additional context in comments.

14 Comments

Good catch - adding a leading and trailing space to the strings in exclude, then replacing with a single space, would give the expected result.
I think you mean two of which are empty strings.
str_replace(" ", " ", str_replace($exclude,"", trim($search_string))) Replace any double-spaces with just one space. Then continue as-is. @html-tosin
@Anonymous Ah, yeah. on is replaced as well, so you got actually two sequences of two spaces, each resulting in an empty string in the expoded string.
I just used var_dump now, and discovered that what u are saying is VERY TRUE
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.