0

What is the best way to split the below $string to get the array $cars in PHP?

$string = '{xa}{y}{z12}{123}{2}{aabb}';

$cars = array("{xa}","{y}","{z12}", "{123}", "{2}", "{aabb}");

I need each array element with brackets eg : {xa}

2
  • Maybe something like preg_match_all("/\{.\}/", $string, $x);. Commented Jul 28, 2014 at 15:05
  • preg_split()? since your delimiters aren't the same throughout, you can't really use explode(). Commented Jul 28, 2014 at 15:10

1 Answer 1

5
$string = str_replace("}{","},{",$string);
$x = explode(',',$string);
Sign up to request clarification or add additional context in comments.

4 Comments

I need each array element with brackets eg : {xa}
@MDeSilva This will preserve brackets.
Isn't that good to use preg_split() to do the job ? which one is the best ?
@MDeSilva Regex is usually slower than doing linear operations like string replacement.

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.