【问题标题】:Make all img tags' src attributes contain absolute paths使所有 img 标签的 src 属性包含绝对路径
【发布时间】: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-&gt;attributes-&gt;name == "src") echo $image-&gt;attributes-&gt;value;

标签: php replace html-parsing domdocument src


【解决方案1】:

绝对不要在此任务中使用正则表达式。结合使用 DOMDocument 和 XPath 可以快速完成这项任务,并且语法相当直观。如果任何&lt;img&gt; 标记的src 属性不start with 您预先声明的域,则从src 值的前面修剪任何正斜杠并在域前添加以形成绝对路径。

代码:(Demo)

$html = <<<HTML
<div>
   <img src="image/abc.png" alt="test" width="50" height="50">
   <img src="http://example.com/image/abc.png" alt="test" width="50" height="50">
   <img src="/image/abc.png" alt="test" width="50" height="50">
   <iframe src="image/abc.png" alt="test" width="50" height="50"></iframe>
</div>
HTML;

$base = "http://example.com/";

$dom = new DOMDocument; 
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//img[not(starts-with(@src, '$base'))]") as $node) {
    $node->setAttribute('src', $base . ltrim($node->getAttribute('src'), '/'));
}
echo $dom->saveHTML();

输出:

<div>
   <img src="http://example.com/image/abc.png" alt="test" width="50" height="50">
   <img src="http://example.com/image/abc.png" alt="test" width="50" height="50">
   <img src="http://example.com/image/abc.png" alt="test" width="50" height="50">
   <iframe src="image/abc.png" alt="test" width="50" height="50"></iframe>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2023-03-03
    • 2021-03-22
    • 1970-01-01
    • 2015-10-02
    相关资源
    最近更新 更多