dongxian4531 2012-05-25 13:38
浏览 44
已采纳

正则表达式在PHP中没有正确评估

I'm having a problem with PHP regular expression matching.

The problem I'm trying to solve is I that I need to get a decimal value from a string. The expression needs to meet all the following (all dollar signs optional):

($)1234.56
($)1,234.56
($)1.00
($)10
($).49
($)1,234,567.32
($)1,234,567

After finding some wonderful examples online, I was able to Frankentstein this expression together:

/(?:^|\s|\$)([1-9](?:\d*|(?:\d{0,2})(?:,\d{3})*)(?:\.\d*[0-9])?|0?\.\d*[0-9]|0)(?:\s|$)/

If you use this preg_match tester on solmetra, using the above pattern and the test string 'per unit price $19198.01 hey!' you will will get the following result:

Array
(
    [0] => $19198.01 
    [1] => 19198.01
)

Which is great - it's exactly what I need!

However, when I run the below code in PHP 5.3.10, I get null as an output for matches using this pattern string:

Code:

  $pattern = '/(?:^|\s|\$)([1-9](?:\d*|(?:\d{0,2})(?:,\d{3})*)(?:\.\d*[0-9])?|0?\.\d*[0-9]|0)(?:\s|$)/';
  $subject = 'per unit price $19198.01 hey!';
  $matches = preg_match($pattern,$subject);                
  var_dump($matches[0]); //dumps "null"

I'm sure I'm doing something wrong, but I just can't see it.

Any help would be greatly appreciated.

Environment:

PHP  5.3.10
Apache 2.2.21
Windows 2008 Server
  • 写回答

1条回答 默认 最新

  • duan5731 2012-05-25 13:42
    关注

    Your error is just in the function usage:

     $matches = preg_match($pattern,$subject);   
    

    What you are actually getting there is:

     $booleanresult = ...
    

    But you need the third param to preg_match for the actual outcome:

     $bool = preg_match($pattern, $subject, $matches);   
    

    And voila, your regex does actually work. I'd additionally recommend the /x flag to make it a bit more readable though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料