【问题标题】:PHP preg_match_all to extract number with or without decimal [duplicate]PHP preg_match_all 提取带或不带小数的数字[重复]
【发布时间】:2016-05-17 08:12:09
【问题描述】:

我正在尝试从字符串中提取任何数字(带或不带小数)并将其转储到数组中。下面是我的代码

$matches = array();
$str = "I have string of 21.11 out of 30";
preg_match_all("/\d+/",$str,$matches);
echo var_dump($matches);

当前输出有以下3个元素:

21

11

30

但我希望只输出以下 2 个元素:

21.11

30

如何更改我的正则表达式?

【问题讨论】:

  • 试试[-+]?[0-9]*\.?[0-9]*

标签: php regex


【解决方案1】:

你应该使用这个正则表达式(在字符类中添加点):

$matches = array();
$str = "I have string of 21.11 out of 30";
preg_match_all("/[\d\.]+/",$str,$matches);
var_dump($matches);

Test it (Ctrl + Enter)

【讨论】:

  • 只是不需要回应var_dump 但很好的解决方案。
  • 你是对的,这是多余的。
  • 谢谢,Jedema,它有效!
  • 嗨,Jedema,如果我想只用数字提取数字并忽略带数字的单词呢?例如,那些带有数字的单词,例如“d7”或“abc100”,我不想提取数字,因为它是单词的一部分。
  • 它不是很优雅,但很有效:tehplayground.com/#5YuA8Oaq9
猜你喜欢
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 2021-12-10
  • 1970-01-01
  • 2017-11-14
  • 2022-11-03
  • 1970-01-01
相关资源
最近更新 更多