我一直在编写一个帖子编辑器,我想从html代码中插入的所有图像生成缩略图,所以,在此之前我想获得所有基本图像属性
示例:
$mydomain = 'mysite.com';
$htmlcode = <<<EOD
<p>sample text</p>
<img src='/path/to/my/image.ext' width='120' height='90' />
<hr />
<img src='html://www.mysite.com/some/ther/path/image.ext' /> <!-- no attributes -->
<hr />
<p>blah blah <img src="http://www.notmyserver.com/path/lorem-ipsum.ext" widht='120' height='90' /></p>
EOD;
function get_all_image_attributes($htmlcode){
// some code...
return $images; // array with image src (required), width (if has), heigth (if has)...
}
// then validate (I really need this part)
$images = get_all_image_attributes($htmlcode);
function verify($images,$mydomain){
// code...
return $valid_images;
}
有效图片为(.jpg,.jpeg,.gif,.png)
SRC = “/路径/ image.ext”
SRC = “http://www.mysite.com/path/image.ext”
SRC = “http://www.mysite.com/some/path/image.ext”
SRC = “http://mysite.com/some/path/image.ext”
SRC = “www.mysite.com/path/image.ext”
PS。
生成缩略图的部分已经完成,不用担心:)
//I have done the following
$html = str_get_html($html);
$images = $html->find('img');
foreach ($images as $image){
$filename = getfilename($image);
// I would like validate the file if is located in other path,
// or if it contains 'http://[www.]mysite.com/'
if(file_exists(PUBLICPATH.'post_images/'.$filename))
valid_imgs[] = BASEURL.'post_images/'.$filename;
}
function getfilename($full_filename){
$filename = substr( strrchr($full_filename , "/") ,1);
if(!$filename)
$filename = $full_filename;
$filename = preg_replace("/^[.]*/","",$filename);
return $filename;
}
答案 0 :(得分:3)
使用HTML解析器。使用PHP Simple HTML DOM Parser,您可以执行以下操作:
$html = str_get_html($htmlcode);
foreach($html->find('img') as $element) {
verify_image($element->src);
}
答案 1 :(得分:0)
这样的事情可能会很好:
#!/usr/bin/perl
open(F, 'tmp.txt');
while(<F>) {
while (m/img[^>]* src="([^"]+)"/g) {
my $imgurl = $1;
verify_image($imgurl);
}
}
答案 2 :(得分:0)
public function GetImagesFromHTML($strHTMLContent) {
$HTMLDOM = new DOMDocument();
$HTMLDOM->loadHTML($strHTMLContent);
$arrContentImages = array();
foreach ($HTMLDOM->getElementsByTagName("img") as $objImage) {
$arrContentImages[] = $objImage->getAttribute("src");
}
return (!empty($arrContentImages)) ? $arrContentImages : false;
}
我已经看到了一些关于将DOM对象转换为SimpleXML的建议,所以你可以使用Xpath,我试过它,虽然它工作但它仍然需要进一步处理结果嵌套对象,这只是为服务器增加了更多的工作,如果所有你关心的是为一块HTML中的所有图像获取src的值,所以我编写了上面的函数来完成这项工作,不需要转换为XPath,只需使用PHP5内置的DOM解析器并给你返回一个像:
这样的数组Array(
[0] => value1.jpg
[1] => value2.jpg
[2] => value3.jpg
[3] => res/upload.jpg
[4] => value4.jpg
[5] => value5.jpg
[6] => value6.jpg
)
函数的总执行时间0.00071001052856445秒