4

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;"
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
suamikim
  • 5,350
  • 9
  • 40
  • 75

4 Answers4

7

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

mellamokb
  • 56,094
  • 12
  • 110
  • 136
6

Just use the trim function first to cut away the white space at the end.

$trimmed_tags = trim($tags);

Zevi Sternlicht
  • 5,399
  • 19
  • 31
2

Fastest way:

$tagsArr = array_filter( explode(' ', $tags) );
iimos
  • 4,767
  • 2
  • 33
  • 35
0

It appears you wish to retain white space throughout the string, but remove from the end (to prevent this last annoying semi colon. If I have understood correctly so far, this sounds like the perfect use for the trim command:

http://php.net/manual/en/function.trim.php

SamuelDavis
  • 3,312
  • 3
  • 17
  • 19