Tilman Koester
Tilman Koester

Reputation: 1739

PHP - Normalize user input array

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?

Upvotes: 1

Views: 886

Answers (3)

BoltClock
BoltClock

Reputation: 723729

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]);

Upvotes: 2

Massimog
Massimog

Reputation: 166

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

Upvotes: 0

Dan Grossman
Dan Grossman

Reputation: 52372

On each string:

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

Then read $matches[1] for the numbers

Upvotes: 4

Related Questions