gpt4 book ai didi

php - 当模式涉及美元符号 ($) 时,正则表达式失败

转载 作者:IT王子 更新时间:2023-10-29 00:00:52 28 4
gpt4 key购买 nike

在匹配涉及美元符号的子模式时,我遇到了一些问题。例如,考虑以下文本 block :

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("/正常价格:\$(\d+\.\d{2}).*最终价格:\$(\d+\.\d{2})/U", $data, $matches );

我逃脱了美元符号,那又如何呢?

最佳答案

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

关于php - 当模式涉及美元符号 ($) 时,正则表达式失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5358010/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com