我想在preg_match_all的模式中包含變量。我已經嘗試了幾種方法,而且它們都不起作用 - 即使這種模式在回聲上是正確的。如何在php中使用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);
問題:雙引號前$得到逃脫。奇怪的。
我做了我的研究,並嘗試了其他一些方法,包括使用大括號{},但無濟於事。
我如何得到這個工作?
謝謝!
另請參見[你能提供一些例子爲什麼很難用正則表達式分析XML和HTML?](http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse -xml-and-html-with-a-reg) – deceze 2012-03-01 01:44:52
「它看起來很好」。它顯然不是很好。否則會起作用。 – 2012-03-01 01:44:55
看起來你有點過分偏執,你的逃跑在那裏。我不認爲你需要轉義'<或'='。如果您可以給我們提供'$ code'和'$ contents'的示例值,那麼我們可以更容易地提供幫助。 – 2012-03-01 01:45:24