-2

Im tring to use preg_match to grab image URLs from another page but problem is my PHP code always returns an empty result! I'm new to php.

Here is the stucture of the image on that page...

<a class="prs_link" href="xxxx"><img src="THE IMAGE URL I WANT TO GET" width="310" height="196"></a>

My current code is:

preg_match_all('/a class="prs_link" href="([^"]+)"><img src=.+?><\/a>/',$screen,$results);
Ben
  • 51,770
  • 36
  • 127
  • 149
Dilon Perera
  • 73
  • 1
  • 8

1 Answers1

1

You will see literally hundreds of Q&A here on SO cautioning coders using regex to parse HTML. There is a good reason of those comments/answers so please adhere to that and avoid finding regex solution to parse out HTML.

Here is one recommended way of parsing HTML (using DOM):

$html = '<a class="prs_link" href="xxxx"><img src="THE IMAGE URL I WANT TO GET" width="310" height="196"></a>';
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//a[@class='prs_link']/img/@src)");
echo "src=[$src]\n";

Output:

src=[THE IMAGE URL I WANT TO GET]
anubhava
  • 761,203
  • 64
  • 569
  • 643