0

I have a number of items in a table, formatted like this

<td class="product highlighted">
Item Name
</td>

and I am using the following PHP code

$regex_pattern = "/<td class=\"product highlighted\">(.*)<\/td>/";
preg_match_all($regex_pattern,$buffer,$matches);
print_r($matches);

I am not getting any output, yet I can see the items in the html.

Is there something wrong with my regexp?

user813813
  • 323
  • 1
  • 8
  • 28
  • I smell that something like that has been asked numerous times... . Please use the search. – hakre Sep 12 '11 at 20:53
  • E.g. [How to make dot match newline characters using regular expressions](http://stackoverflow.com/questions/1985941/how-to-make-dot-match-newline-characters-using-regular-expressions) – mercator Sep 12 '11 at 21:02

2 Answers2

6

Apart from your using regex to parse HTML, yes, there is something wrong: The dot doesn't match newlines.

So you need to use

$regex_pattern = "/<td class=\"product highlighted\">(.*?)<\/td>/s";

The /s modifier allows the dot to match any character, including newlines. Note the reluctant quantifier .*? to avoid matching more than one tag at once.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • @user813813 For reference, see the documentation about the [dot in PHP regex syntax](http://www.php.net/manual/en/regexp.reference.dot.php), and [pattern modifiers](http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php). – mercator Sep 12 '11 at 20:51
3

In order to match your example, you will need to add the dot all flag, s, so the . will match newlines.

Try the following.

$regex_pattern = "/<td class=\"product highlighted\">(.*?)<\/td>/s";

Also note that I changed the capture to non-greedy, (.*?). It's best to do so when matching open ended text.

It's worth noting regular expressions are not the right tool for HTML parsing, you should look into DOMDocument. However, for such a simple match you can get away with regular expressions provided your HTML is well-formed.

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174