问题
Let's say i have many images in a string and i only want to get the src of the image with a specific class
<img src="image1.jpg"/>
<img src="image2.jpg"/>
<img src="image3.jpg" class="main"/>
I wanted to get the src of the third one, which has a class main
. How do i do that?
$pattern = '/< *img[^>]*src *= *["\']?([^"\']*)/i';
preg_match($pattern,$response,$matches);
this one matches all img tags.
回答1:
Don't use a regex to parse HTML. Use DOMDocument instead.
Here's some code:
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xp = new DOMXPath($dom);
$imgs = $xp->query("//img[@class='main']");
$imgs
now has a NodeList of images with the main
class. (I think - I haven't used DOMXPath much)
来源:https://stackoverflow.com/questions/8867650/preg-match-get-src-of-img-with-specific-class