我想从一个包含数字和字母的字符串中提取数字,比如:

"In My Cart : 11 items"

我想提取数字11。


当前回答

我们可以从它中提取int

$string = 'In My Car_Price : 50660.00';

echo intval(preg_replace('/[^0-9.]/','',$string));  # without number format   output: 50660
echo number_format(intval(preg_replace('/[^0-9.]/','',$string)));  # with number format  output :50,660

演示:http://sandbox.onlinephpfunctions.com/code/82d58b5983e85a0022a99882c7d0de90825aa398

其他回答

根据你的用例,这也是一种选择:

$str = 'In My Cart : 11 items';
$num = '';

for ($i = 0; $i < strlen($str); $i++) {

    if (is_numeric($str[$i])) {
        $num .= $str[$i];
    }
}

echo $num; // 11

尽管我同意regex或filter_var()在上述情况下更有用。

preg_replace('/[^0-9]/', '', $string);

这应该做得更好!

使用preg_replace

$str = 'In My Cart : 11 12 items';
$str = preg_replace('/\D/', '', $str);
echo $str;

对于utf8 str:

function unicodeStrDigits($str) {
    $arr = array();
    $sub = '';
    for ($i = 0; $i < strlen($str); $i++) { 
        if (is_numeric($str[$i])) {
            $sub .= $str[$i];
            continue;
        } else {
            if ($sub) {
                array_push($arr, $sub);
                $sub = '';
            }
        }
    }

    if ($sub) {
        array_push($arr, $sub); 
    }

    return $arr;
}
preg_match_all('!\d+!', $some_string, $matches);
$string_of_numbers = implode(' ', $matches[0]);

在本例中,implode中的第一个参数表示“用单个空格分隔匹配[0]中的每个元素。”Implode不会在第一个数字之前或最后一个数字之后放置空格(或任何你的第一个参数)。

另外需要注意的是$matches[0]是存储匹配数组(匹配此正则表达式)的地方。

有关数组中其他索引的进一步说明,请参阅:http://php.net/manual/en/function.preg-match-all.php