在匹配涉及美元符号的子模式时,我遇到了一个问题.例如,考虑以下文本块:
I'm running into a bit of an issue when it comes to matching subpatterns that involve the dollar sign. For example, consider the following chunk of text:
Regular Price: $20.50 Final Price: $15.20 Regular Price: $18.99 Final Price: $2.25 Regular Price: $11.22 Final Price: $33.44 Regular Price: $55.66 Final Price: $77.88我试图用以下正则表达式匹配常规/最终价格集,但根本不起作用(根本没有匹配项): preg_match_all("/Regular Price: \$(\d+\.\d{2}).*Final Price: \$(\d+\.\d{2})/U", $data, $matches);
I was attempting to match the Regular/Final price sets with the following regex, but it simply wasn't working (no matches at all): preg_match_all("/Regular Price: \$(\d+\.\d{2}).*Final Price: \$(\d+\.\d{2})/U", $data, $matches);
我逃脱了美元符号,那又能给什么呢?
I escaped the dollar sign, so what gives?
推荐答案在双引号字符串内,反斜杠被视为$的转义字符.即使在preg_match_all函数看到反斜杠之前,PHP解析器也会删除反斜杠:
Inside a double quoted string the backslash is treated as an escape character for the $. The backslash is removed by the PHP parser even before the preg_match_all function sees it:
$r = "/Regular Price: \$(\d+\.\d{2}).*Final Price: \$(\d+\.\d{2})/U"; var_dump($r);输出( ideone ):
"/Regular Price: $(\d+\.\d{2}).*Final Price: $(\d+\.\d{2})/U" ^ ^ the backslashes are no longer there要解决此问题,请使用单引号字符串而不是双引号字符串:
To fix this use a single quoted string instead of a double quoted string:
preg_match_all('/Regular Price: \$(\d+\.\d{2}).*Final Price: \$(\d+\.\d{2})/U', $data, $matches);查看其在线运行情况: ideone
See it working online: ideone
更多推荐
正则表达式在模式涉及美元符号($)时失败
发布评论