0

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!

alan
  • 353
  • 2
  • 5
  • 9
  • 1
    Also see [Can you provide some examples of why it is hard to parse XML and HTML with a regex?](http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-reg) – deceze Mar 01 '12 at 01:44
  • 2
    "and it looked fine" .. well it obviously wasn't fine. otherwise it would work. – Karoly Horvath Mar 01 '12 at 01:44
  • 1
    Looks like you're a little overly paranoid with your escaping there. I don't think you need to escape `<` or `=`. If you could give us sample values for `$code` and `$contents` it'd be easier for us to help. – Frank Farmer Mar 01 '12 at 01:45
  • 2
    `even when the pattern is correct upon echo.` -- give an example for correct pattern and text it should match – zerkms Mar 01 '12 at 01:46

1 Answers1

2

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

Brad Christie
  • 100,477
  • 16
  • 156
  • 200