![](/img/trans.png)
[英]PHP function to retrieve all images and their attributes from given html string and save to array and returns array
[英]retrieve all images path from string with PHP
如何从字符串获取所有图像路径? 注意我只想要包含单词“ media”的路径。
例如,给定此字符串(DOM的一部分)
<div class="my-class">
<img src="http://my-website.com/cache/media/2017/10/img67.jpeg" class="" alt="test" width="120" height="100">
<img src="http://my-website.com/cache/2017/10/img68.png" class="" alt="test" width="120" height="100">
<img src="http://my-website.com/cache/media/2017/10/img69.jpg" class="" alt="test" width="120" height="100">
<h2 class="uk-margin-top-remove">About us</h2>
</div>
我想要一个包含类似结果的数组:
array(
[0] => "http://my-website.com/cache/media/2017/10/img67.png"
[1] => "http://my-website.com/cache/media/2017/10/img69.png"
);
我不想要第二个img,因为src属性不包含单词“ media”。
您可以使用preg_match_all()
来获取URL,但使用DOM阅读器甚至更好。
$str = '<div class="my-class">
<img src="http://my-website.com/cache/media/2017/10/img67.jpeg" class="" alt="test" width="120" height="100">
<img src="http://my-website.com/cache/2017/10/img68.png" class="" alt="test" width="120" height="100">
<img src="http://my-website.com/cache/media/2017/10/img69.jpg" class="" alt="test" width="120" height="100">
<h2 class="uk-margin-top-remove">About us</h2>
</div>' ;
$matches = [] ;
preg_match_all('~(http\://my-website\.com/cache/media/(.*?))"~i', $str, $matches) ;
var_dump($matches[1]);
将返回:
array(2) {
[0]=>
string(52) "http://my-website.com/cache/media/2017/10/img67.jpeg"
[1]=>
string(51) "http://my-website.com/cache/media/2017/10/img69.jpg"
}
一些样板代码可以帮助您入门:
<?php
$data = <<<DATA
<div class="my-class">
<img src="http://my-website.com/cache/media/2017/10/img67.jpeg" class="" alt="test" width="120" height="100">
<img src="http://my-website.com/cache/2017/10/img68.png" class="" alt="test" width="120" height="100">
<img src="http://my-website.com/cache/media/2017/10/img69.jpg" class="" alt="test" width="120" height="100">
<h2 class="uk-margin-top-remove">About us</h2>
</div>
DATA;
# set up the dom
$dom = new DOMDocument();
$dom->loadHTML($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);# | LIBXML_COMPACT | LIBXML_NOENT );
# set up the xpath
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//img[contains(@src, '/media/')]/@src") as $image) {
echo $image->nodeValue . "\n";
}
哪个产量
http://my-website.com/cache/media/2017/10/img67.jpeg
http://my-website.com/cache/media/2017/10/img69.jpg
DOM
并为每个图像使用xpath
查询,之后我们将对其进行循环。
DOM
解析器,则可以使用第二好的选择:
<img (?s:(?!>).)+? src=(['"]) (?P<src>(?:(?!\\1).)+?/media/.*?\\1)
并使用src
组,请参阅regex101.com上的演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.