I'm trying to include variables in my pattern for preg_match_all. I've tried several ways and none of them seem to work - even when the pattern is correct upon echo.
Here's what I have:
First Attempt (using single quotes to be safe):
$pattern_areacode = '/\<a name\=\"'. $code . '\"\>'. $code . '\<\/a\>.*?(\<td\b[^>]*\> (.*?)\<\/td\>).*?<\/tr\>/';
preg_match_all($pattern_areacode, $contents, $ac_match);
issue: I printed the pattern and it looked fine. Yet it's not returning any results.
Second Attempt (Using double):
$pattern_areacode = "/\<a name\=\"$code\"\>$code\<\/a\>.*?(\<td\b[^>]*\>(.*?)\<\/td\>).*?<\/tr\>/";
preg_match_all($pattern_areacode, $contents, $ac_match);
issue: The double quotes before $ get escaped. Weird.
I did my research and tried a bunch of other ways as well, including using braces {}, but to no avail.
How do I get this to work?
Thanks!
Make sure your inputs are escaped and don't contain anything that regex may interpret as a pattern (which could make your match fail). This can be done easily using preg_quote
. So, if you haven't already:
$code = preg_quote($quote);
Also, I recommend using an actual HTML parser as opposed to regex matches, maybe look in to using the DOMDocument
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.