0

$_GET['search'] imports the following string: "first second \ \ third" (the spaces between "second" and "third" are just blank spaces, the slashes are added since SO's text area does not allow multiple consecutive blank spaces).

The following script is then to process the imported string:

$searchString = $_GET['search'];
$searchString = preg_replace('/(\W)(\S)(\s+)/', '', $searchString);
echo $searchString . ' ';
print_r( explode(' ', $searchString) );

Which, strangely, results in:

first second third Array ( [0] => first [1] => second [2] => [3] => [4] => third )

I.e. the blank spaces are removed, as anticipated, from $searchString when echoing it, but PHP's explode seems to "re-insert" them. How can this be?

Matte
  • 279
  • 6
  • 16
  • I'm not convinced that what you're "seeing" is what's actually happening. What do you see if you `echo $searchString` *before* you do the `preg_replace`? (Bear in mind that multiple consecutive spaces in an HTML document are [typically rendered as a single space](http://stackoverflow.com/questions/433493/why-do-multiple-spaces-in-an-html-file-show-up-as-single-spaces-in-the-browser).) – Matt Gibson Apr 10 '13 at 13:55
  • @Matt Gibson Exactly the same results, blank spaces removed. – Matte Apr 10 '13 at 13:57
  • 1
    Yes. Which means that the preg_replace isn't actually doing what you think it's doing. It's your browser that is condensing the multiple spaces down to a single space when it's showing you the output. They're there from start to finish, which is why `explode` is still finding them. – Matt Gibson Apr 10 '13 at 13:59
  • Makes sense... I'll tick it as 'correct answer' if you'll post it as one! – Matte Apr 10 '13 at 14:00
  • I think Scott's answer sums things up nicely. I'd just accept that one. – Matt Gibson Apr 10 '13 at 14:03
  • True. It just came in. I'll do that. Thanks for the help, though! – Matte Apr 10 '13 at 14:04
  • 2
    When you're testing stuff like this in the browser, wrap the string in
     tags so the whitespace is more visible.
    – Scott Saunders Apr 10 '13 at 14:05

2 Answers2

4

An easy fix is to use array_filter() to remove the empty array values:

$new_array = array_filter(explode(' ', $searchString));
John Conde
  • 217,595
  • 99
  • 455
  • 496
3

I don't think your regex is doing what you think. Or maybe you should explain what it's supposed to be doing. If you want to remove multiple spaces, use this:

$searchString = preg_replace('/\s\s+/', ' ', $searchString);
Scott Saunders
  • 29,840
  • 14
  • 57
  • 64
  • Works excellent! Thanks for the help. I'll tick correct as soon as the system allows for it! – Matte Apr 10 '13 at 14:04