我正在尝试在preg_match_all的模式中包含变量。我试过几种方法,但似乎都不起作用——即使回声模式正确。
这是我的:
第一次尝试(为了安全起见,使用单引号):
$pattern_areacode = '/'<a name'='"'. $code . ''"'>'. $code . ''<'/a'>.*?('<td'b[^>]*'> (.*?)'<'/td'>).*?<'/tr'>/';
preg_match_all($pattern_areacode, $contents, $ac_match);
问题:我打印了图案,看起来不错。然而,它并没有返回任何结果。
第二次尝试(使用替身):
$pattern_areacode = "/'<a name'='"$code'"'>$code'<'/a'>.*?('<td'b[^>]*'>(.*?)'<'/td'>).*?<'/tr'>/";
preg_match_all($pattern_areacode, $contents, $ac_match);
问题:$get转义之前的双引号。奇怪的
我做了研究,也尝试了很多其他方法,包括使用牙套,但都无济于事。
我该如何让它发挥作用?
谢谢!
确保您的输入是转义的,并且不包含任何regex可能解释为模式的内容(这可能会导致匹配失败)。使用CCD_ 1可以很容易地做到这一点。所以,如果你还没有:
$code = preg_quote($quote);
此外,我建议使用实际的HTML解析器,而不是regex匹配,也许可以考虑使用DOMDocument