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

"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

其他回答

顶级资源友好型解决方案

<?php
    var $string = "In My Cart : 11 items";
?>

1. 最快:filter_var -使用指定的过滤器过滤变量

<?php
    filter_var($string, FILTER_SANITIZE_NUMBER_INT); // string(2) "11"
?>

2. 几乎是最快的:str_replace—用替换字符串替换所有搜索字符串

<?php
    str_replace(array('In My Cart : ',' item', 's'),"", $string); // string(2) "11"
?>

3.足够快:preg_replace -执行正则表达式搜索和替换

<?php
    preg_replace("/[^0-9]/","",$string); // string(2) "11"
?>

然而

str_replace的简单性导致速度加快,但用例也有限 Preg_replace比str_replace或filter_var更通用 相反,可以使用preg_replace_callback函数指定要替换的内容 使用preg_replace_callback可以在一次调用中执行多个替换 Filter_var在环卫选项中受限

如果你不知道数字的格式?Int或float,然后使用这个:

$string = '$125.22';

$string2 = '$125';

preg_match_all('/(\d+.?\d+)/',$string,$matches); // $matches[1] = 125.22

preg_match_all('/(\d+.?\d+)/',$string2,$matches); // $matches[1] = 125
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

你可以使用preg_match:

$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);

试试这个,使用preg_replace

$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;

DEMO