How to limit the elements created by explode()
Asked Answered
F

4

0

If i have a string like

"1234 Name Extra"

And i do

list($postcode, $city) = explode(" ", $string);

It turns out that $postcode is "1234" and $city is "Name". I would like $city to be "Name Extra"

How can i do this?

Foil answered 10/12, 2011 at 13:33 Comment(2)
Consider using regular expression to determine what is what. php.net/manual/en/function.preg-replace.phpCommissure
php.net/manual/en/function.explode.phpRoe
N
12

Use the third parameter ($limit) of explode. The resulting array will have $limit Elements.

list($postcode, $city) = explode(" ", $string, 2);
Nighttime answered 10/12, 2011 at 13:37 Comment(0)
C
3
list($postcode, $city) = explode(" ", $string, 2);
Canoness answered 10/12, 2011 at 13:36 Comment(1)
Please always post some semblance of an explanation with your answers. Code-only answers do very little to educate future readers.Neddy
T
2

If you look at the PHP docs, you'll see that explode() has an optional third parameter that specifies how many times you want to explode.

Tonguelashing answered 10/12, 2011 at 13:35 Comment(0)
L
2

From the manual:

array explode ( string $delimiter , string $string [, int $limit ] )

so you use the optional limit argument, in your case 2, I believe

Logbook answered 10/12, 2011 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.