0

我有一个函数:函数从字符串行返回数字。

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

我需要将数字放入我的 php 文件中的数组中。怎么做?

$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 可以工作,但 $user_count[$sk] 行可能是 "15, 16, 19, 14,16"; 即它可能包含也可能不包含空格。

4

2 回答 2

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)
于 2013-07-28T07:47:34.020 回答
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

于 2013-07-28T07:47:44.590 回答