Regex for Space Separated List

This may be impossible, or I may be special.

So, I basically want to match a pattern where I have one or more space separated values. I’d like to use either preg_match or preg_match_all to get each value, separated.

I can easily get them all together (which I could then split), but is there a way to do it with one call that I’m just missing?


Can you give an example string? \s is the space/tab/line break match for perl regular expressions.

Basically something like:

“something a b c d”

I would use a pattern like:

preg_match("/something ([^\\s]+)/", $str, $matches);

which would make $matches[1] equal “a b c d”.

I’d like to somehow make it so $matches would contain “a”, “b”, “c”, “d” all separately. I can do it with two matches (making the second just match spaces), but I can’t get it to do it in one.


split() (the opposite of join()) is what you’re looking for. Without removing "something " from the $str, the assignment array will have split[1] = “something” before you get to your meaningful values.



Thanks DK. I think you mean split[0], but yeah.

My example was overly simplistic, I’d have to do some regex to get that list of space separated values. I can easily split them afterwards (multiple whitespace characters between the values are valid, so I need to use regex to split them as well, since a simple split on " " won’t work).

I was just hoping I could combine those two regex into one some how. =p

[fphp]fgetcsv[/fphp] - the 3rd argument can be a space if you want, further down that page are links to similar functions which may help you.

I’m not sure, reading your examples, if this is what you’re looking for (but it might be, and if it is… score).

$regex = '/(?<=\\s)\\S+/';
$subject = 'something a b c d';

preg_match_all($regex, $subject, $matches);

Uhm… isn’t this more a job for explode? It’s space delimited, blow it apart into an array with explode.

$list=explode(' ',$str);
echo '<pre>',print_r($list),'</pre>';

Hey look, you got an array.

The problem is it isn’t required to be single space, it can be any number of whitespace characters (hence using regex to use \s+).