I want to split a string into two parts, the string is almost free text, for example:
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:
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.
I tried using this regex: /(\S*)\s*(\.*)/ but even though the returned array is the correct size, The value is also empty.
What should be the pattern necessary to make this works?
What should be the pattern to make this effective?
2 solutions
#1
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
:
What are the requirements? Your example seems very arbitrary. If all you want is to split on the first space and leave the rest of the string, then use explode:
$pieces = explode(' ', 'hi how are you', 2);
Which basically says “split on spaces and limit the resulting array to 2 elements”
This basically says “split on spaces and limit the resulting array to 2 elements”
#2
You should not be escaping the “.” in the last group. You’re trying to match any character, not a literal period.
You should not escape the “.” in the last group. You’re trying to match any character, not the literal period.
Corrected: /(\S*)\s*(.*)/