0

First, I know I can get the very same result with explode, just want to know why it is not working in PHP

preg_split('/(.+,)+(.+)/im', 'New York, NY, United States');

It returns

array (
  0 => '',
  1 => '',
)

Why? It should returns: ['New York, NY, ', 'United States'] right?

3 Answers 3

1

Using preg_split you can make : preg_split("/,\s/", 'New York, NY, United States');

This function needs the pattern of the separator.

Sign up to request clarification or add additional context in comments.

3 Comments

This is not giving the array given by OP ie. ['New York, NY, ', 'United States'] that have only two elements.
With preg_split the 'limit' parameter set to default value '-1' will return all the 3 results on array.
In OP's question the array is TWO element long, 1rst is New York, NY, the second one is United States
1

You are actually doing a match for what you want, not on what you want to use to split:

preg_match('/(.*,)+ (.*)/', $subject, $result);

would get the matches in $result

note: I've added a space and removed the multi line modifiers, there are not needed in your case.

If you want to use preg split, you need to use a negative lookahead to get the last ,:

preg_split('/(,)(?!.*,)/i', 'New York, NY, United States');

Comments

0

In order to get the array: ['New York, NY, ', 'United States'], remove the second quantifier and use preg_match instead:

preg_match('/^(.+,)(.+?)$/im', 'New York, NY, United States', $match);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.