preg_match decimals not working

隐身守侯 提交于 2020-01-06 03:04:22

问题


I seem to be having a problem with a preg_match code, I am trying to get the decimal number from a string which should be something like '3.25' but instead I get '1'

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

prints "1"


回答1:


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

gives

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

even on PHP 5.2 : http://codepad.viper-7.com/9nFhET




回答2:


First, you'll find the value at the index 1 of the array ( $matches[1] )

Try something like that :

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

That gives :

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



回答3:


I can repro an issue with decimals on this tester site:
http://www.pagecolumn.com/tool/pregtest.htm

If you replace the escaped dot with a character class that contains a dot it works:

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

Btw: is it possible that you get the dot but no digits after it ?
If not I would replace the [0-9]* with either [0-9]+ or a specific number of digits expected [0-9]{2}



来源:https://stackoverflow.com/questions/10371476/preg-match-decimals-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!