preg_match get src of img with specific class

霸气de小男生 提交于 2019-12-24 19:37:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!