user1980781
user1980781

Reputation:

PHP regex - how can I separate zip and cityname?

How can I separate this data:

12345 cityname
54321 anothercityname

I tried this regex: /(\d{5}?),\s*([^,]+)/

but it doesn't work.

Upvotes: 1

Views: 57

Answers (2)

vks
vks

Reputation: 67968

You have defined a , in your regex after \d{5} but it is not there in your string.So it will not match.make it optional by adding ? to it.

See the improved one for your needs

http://regex101.com/r/nG1gU7/8

Upvotes: 1

René Höhle
René Höhle

Reputation: 27295

I think you will seperate your data to zip and city? Then its easier to explode it.

$sep = explode(' ', $string);
$zip = $sep[0];
$city = $sep[1];

the mistake in your regex is that you have a comma in it.

/(\d{5}?),\s*([^,]+)/

between your digits and your string. But you have no comma in your string. Make them optional with a ? something like this:

/(\d{5}?),?\s*([^,]+)/

Upvotes: 0

Related Questions