Delimit string with spaces

What would be a suitable regular expression to split a string into all spaces? There may also be several spaces between the two tokens, and in the end, spaces should be ignored.

What I still have:

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

This gives me the following result:

 "unread;dev;test1;;" 

As you can see, this does not ignore spaces at the end, because the correct output should be:

 "unread;dev;test1;" 
+4
source share
4 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

+7
source

Just use the crop function first to cut the space at the end.

$ trimmed_tags = trim ($ tags);

+6
source

The fastest way:

 $tagsArr = array_filter( explode(' ', $tags) ); 
+2
source

It looks like you want to keep the space in the entire line, but remove from the end (to prevent this last annoying partial shade. If I understood correctly so far, this sounds like the perfect use of the trim command:

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

0
source

All Articles