【发布时间】:2014-01-01 08:35:08
【问题描述】:
我正在尝试从页面获取/替换图像源链接。
某些页面有图片src='image/abc.png',所以我的正则表达式失败了。
我想要做的是:如果没有给出绝对路径,则将子目录路径附加到主 url。
即如果src='image/abc.png 和主网址是http://example.com
那么它应该转换为http://example.com/image/abc.png
注意:有些用户可能会输入像 http://example.com/ 这样的 url 名称,所以如果我像上面那样附加,那么它将给出:
http://example.com//image/abc.png 这是错误的。
谁能给我正确的方向来形成图像的确切绝对路径?
我的代码:
<?php
function get_logo($html, $url) {
if (preg_match_all('/\bhttps?:\/\/\S+(?:png|jpg)\b/', $html, $matches)) {
echo "First:";
return $matches[0][0];
} else {
if (preg_match_all('~\b((\w+ps?://)?\S+(png|jpg))b~im', $html, $matches)) {
echo "Second: ";
echo $matches[0][0];
return url_to_absolute($url, $matches[0][0]);
//return $matches[0][0];
} else
return null;
}
}
【问题讨论】:
-
使用
DOMDocument代替正则表达式,然后检查每个img的src属性是否以HTTP 开头。 -
@AeroX:请再次阅读问题。
DOM我无法使用,在这里我试图以不同的方式获得解决方案。 -
@AeroX:这是正确的吗?
if( $image->attributes->name == "src") echo $image->attributes->value;
标签: php replace html-parsing domdocument src