简体   繁体   English

从html字符串中检测节点并在PHP中提取图像

[英]Detect node from html string and extract image inside in PHP

I'm locked on something that make me crazy, if you can help me, would be cool ! 我锁定的东西会让我发疯,如果可以帮助我,那将很酷!

I have a string containing a valid HTML code. 我有一个包含有效HTML代码的字符串。 In this PHP code I would like to detect a specific image via the class of his parent, and extract the url of the image + update it with another url. 在此PHP代码中,我想通过其父级的类检测特定的图像,并提取图像的url,然后用另一个url更新它。

Here is an example : 这是一个例子:

$html = '....<div class="header">...<img src="theimage.png" />...</div>...';

I would like to parse the $html string, extract the url "theimage.png" and replace it by "theimage2.png" (after some internal working) 我想解析$ html字符串,提取URL“ theimage.png”并将其替换为“ theimage2.png”(经过一些内部工作)

I tried to use a REGEX, but I'm not sure it's the best solution, because I need to be sure that only the image in .header will be returned, and I need to execute some functions to get the name of the future link. 我尝试使用REGEX,但是我不确定这是最佳解决方案,因为我需要确保仅返回.header中的图像,并且我需要执行一些函数来获取将来链接的名称。 。

Maybe the solution is to parse the HTML with DOM Node, but it didn't work too. 也许解决方案是使用DOM Node解析HTML,但是它也不起作用。

Can you help me please ? 你能帮我吗 ? Thanks !!! 谢谢 !!!

You can achieve this using SimplePHPDom 您可以使用SimplePHPDom实现此目的

PHP 的PHP

$html = '<body><div class="header"><p>some html</p><img src="theimage.png" /></div></body>';
$html_dom = str_get_html($html);

foreach($html_dom->find('.header img') as $element) {
    echo $element->src . '<br>'; // output src of img inside .header div
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM