tags:

views:

73

answers:

2

I want to split a string into two parts, the string is almost free text, for example:

$string = 'hi how are you';

and i want the split to look like this:

array(
    [0] => hi
    [1] => how are you
)

I tried using this regex: /(\S*)\s*(\.*)/ but even when the array returned is the correct size, the values comes empty.

What should be the pattern necessary to make this works?

+5  A: 

What are the requirements? Your example seems pretty arbitrary. If all you want is to split on the first space and leave the rest of the string alone, this would do it, using explode:

$pieces = explode(' ', 'hi how are you', 2);

Which basically says "split on spaces and limit the resulting array to 2 elements"

Paolo Bergantino
+1 - I *hate* the use of regexes when they are just not needed.
karim79
That's a great name for a function. I wish Java had an explode().
Michael Myers
@karim79: I hate that too...@Paolo Bergantino: thanks, thats exactly my requirement.
Cesar
A: 

You should not be escaping the "." in the last group. You're trying to match any character, not a literal period.

Corrected: /(\S*)\s*(.*)/

pix0r