【问题标题】:Getting numbers from string line? PHP从字符串行获取数字? PHP
【发布时间】:2013-07-28 07:41:10
【问题描述】:

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

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";即它可能包含也可能不包含空格。

【问题讨论】:

标签: php string numbers


【解决方案1】:

你不需要正则表达式,explode() 结合str_replace() 就可以了:-

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

输出:-

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)

【讨论】:

    【解决方案2】:

    如果你有一个看起来像这样的字符串:

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

    并且想将它们拆分成一个数组,可以使用explode

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

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

    【讨论】:

    猜你喜欢
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 2016-09-25
    相关资源
    最近更新 更多