1

If have an array like this:

array
  0 => string '62 52, 53' (length=9)
  1 => string '54' (length=2)

It's from user input, and you never know how/what they enter ;)

What I want in the end is this:

array
  0 => string '62' (length=2)
  1 => string '52' (length=2)
  2 => string '53' (length=2)
  3 => string '54' (length=2)

Here's how I do it:

  $string = implode(',', $array);
  $string = str_replace(', ', ',', $string);
  $string = str_replace(' ', ',', $string);
  $array = explode(',', $string);

Seems really clunky. Is there a more elegant way? One that maybe has better performance?

3 Answers 3

4

On each string:

preg_match_all("/[ ,]*(\d+)[ ,]*/", $list, $matches);

Then read $matches[1] for the numbers

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

Comments

2

Not sure about performance but you can use a regex to grab only numbers after you join everything into a string.

$string = implode(' ', $array);
preg_match_all('/\d+/', $string, $matches);
print_r($matches[0]);

Comments

0

You may want to use preg_split and array_merge (PHP 4, PHP 5)

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.