如何使用PHP从字符串中提取数字(例如:10)

如何使用PHP从字符串中提取数字(例如:10),php,Php,我需要从字符串中提取一个数字,该字符串如下所示: $string ="Thank you for your order... order date: 01-01-2019 <br> items: 12 tomatoes<br> price: 5.00 $"; 注意:这是一个问题 假设格式总是“Items:”然后是数字,您可以使用以下preg\u match: $string ="Thank you for your order... order date: 01-01-

我需要从字符串中提取一个数字,该字符串如下所示:

$string ="Thank you for your order... order date: 01-01-2019 <br> items: 12 tomatoes<br> price: 5.00 $";
注意:这是一个问题

假设格式总是“Items:”然后是数字,您可以使用以下
preg\u match

$string ="Thank you for your order... order date: 01-01-2019 items: 12 tomatoes price: 5.00 $";
preg_match("/items: ([0-9]+)/", $string, $matches);
var_dump($matches);
这将从
$matches
数组中输出以下值:

array(2) {
  [0]=>
  string(9) "items: 12"
  [1]=>
  string(2) "12"
}
其中您的编号为
$matches[1]

使用strpos()函数查找“:”,然后使用substr()函数获取接下来的3个字符


此示例表示,从$string中,查找“items:”的位置,然后获取变量$data中的下3个字符,您还可以找到可用于提取(子字符串)所需信息的字符串索引

stripos()-字符串中第一次出现不区分大小写的子字符串

$string ="Thank you for your order... order date: 01-01-2019 items: 12 tomatoes price: 5.00 $";
$firstIndex = stripos($string, ':');
$lastIndex = strripos($string, ' tomatoes');

$count= substr($string, $firstIndex + 2, $lastIndex )
strripos()-字符串中不区分大小写的子字符串的最后一次出现

$string ="Thank you for your order... order date: 01-01-2019 items: 12 tomatoes price: 5.00 $";
$firstIndex = stripos($string, ':');
$lastIndex = strripos($string, ' tomatoes');

$count= substr($string, $firstIndex + 2, $lastIndex )

^^链接重复回答好点。我将在我的答案中链接。这非常有效,我喜欢这个解决方案!如果我想用这个脚本来代替“价格”,我该如何处理digets?我要不带美元标志的5点!这是否有效:preg_match_all('/items:([\d]+)/',$string,$matches);将
preg_match
更改为以下内容:
“/price:([0-9\\.]+)/”
$string ="Thank you for your order... order date: 01-01-2019 items: 12 tomatoes price: 5.00 $";
$firstIndex = stripos($string, ':');
$lastIndex = strripos($string, ' tomatoes');

$count= substr($string, $firstIndex + 2, $lastIndex )