Search code examples
phpregexpreg-split

Delimit string by whitespaces


What would be the appropriate regex to delimit a string by all whitespaces? There can also be more than one whitespace between two token and it should ignore whitespaces at the end.

What I have so far:

<?php
$tags = "unread dev     test1   ";
$tagsArr = preg_split("/ +/", $tags);
foreach ($tagsArr as $value) {
  echo $value . ";";
}

This gives me the following output:

"unread;dev;test1;;"

As you can see it doesn't ignore the whitespaces at the end because the correct output should be:

"unread;dev;test1;"

Solution

  • You can ignore empty entries using the flag PREG_SPLIT_NO_EMPTY:

    $tagsArr = preg_split("/ +/", $tags, -1, PREG_SPLIT_NO_EMPTY);
    

    Demo: http://ideone.com/1hrNJ