preg_match小数不起作用

时间:2012-04-29 10:39:01

标签: php regex preg-match

我似乎遇到了preg_match代码的问题,我试图从一个字符串中得到十进制数,这应该是'3.25',而是我得到'1'

preg_match('/[0-9]+(?:\.[0-9]*)?/', '£3.25', $matches);
echo 'match: '.$matches[0];

打印“1”

3 个答案:

答案 0 :(得分:2)

preg_match('#\d+(?:\.\d{1,2})?#', '£2.35', $match);
var_dump($match);

给出

array(1) {
  [0]=>
  string(4) "2.35"
}

甚至在PHP 5.2上:http://codepad.viper-7.com/9nFhET

答案 1 :(得分:1)

首先,您将在数组的索引1($matches[1]

处找到该值

尝试类似的东西:

<?php
preg_match('/[0-9]+\.([0-9]+)/', '£3.25', $matches);
print_r($matches);
?>

这给出了:

Array
(
    [0] => £3.25
    [1] => 25
)

答案 2 :(得分:0)

我可以在这个测试站点上重复一个小数问题:
http://www.pagecolumn.com/tool/pregtest.htm

如果使用包含点的字符类替换转义点,则可以使用:

[0-9]+(?:[.][0-9]*)?

顺便说一句:你有可能得到这个点但没有数字吗?
如果不是,我会将[0-9]*替换为[0-9]+或预期的特定位数[0-9]{2}