0

I have a function: Function returns numbers from string line.

function get_numerics ($str) {
    preg_match_all('/\d+/', $str, $matches);
    return $matches[0];
}

And I need to get numbers to an array in my php file. How to do that?

$counter = $user_count[$sk]; //$user_count[$sk] gives me a string line
//$user_count[$sk] is "15,16,18,19,18,17" - And i need those numbers seperated to an array
$skarray[] = get_numerics($counter); //Something is wrong?

Explode could work, but $user_count[$sk] line could be "15, 16, 19, 14,16"; ie it may or may not contain spaces.

vascowhite
  • 18,120
  • 9
  • 61
  • 77
user2614879
  • 151
  • 1
  • 2
  • 9

2 Answers2

1

You don't need regex for this, explode() combined with str_replace() will do it:-

$user_count = "15 ,16,18 ,19,18, 17";
$numbers = explode(',', str_replace(' ', '', $user_count));
var_dump($numbers);

Output:-

array (size=6)
  0 => string '15' (length=2)
  1 => string '16' (length=2)
  2 => string '18' (length=2)
  3 => string '19' (length=2)
  4 => string '18' (length=2)
  5 => string '17' (length=2)
vascowhite
  • 18,120
  • 9
  • 61
  • 77
0

if you have a string that looks like:

$str = "15,16,17,18,19";

And want to split them into an array, you can use explode

$arr = explode(",", $str);

see http://www.php.net/manual/en/function.explode.php

TuK
  • 3,556
  • 4
  • 24
  • 24
  • .. i wonder how the **only** "answer" that does not solve OP problem have managed to get an upvote. – tereško Jul 28 '13 at 07:59
  • @tereško It is less rare than you might imagine: https://stackoverflow.com/questions/46095569/how-to-increment-a-letter-n-times-per-iteration-and-store-in-an-array – mickmackusa Oct 15 '17 at 01:43