Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;"
like image 932
suamikim Avatar asked Dec 07 '22 12:12

suamikim


2 Answers

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

like image 156
mellamokb Avatar answered Dec 21 '22 17:12

mellamokb


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

$trimmed_tags = trim($tags);

like image 24
Zevi Sternlicht Avatar answered Dec 21 '22 16:12

Zevi Sternlicht