【问题标题】:php: replace every img src in some conditionphp:在某些情况下替换每个 img src
【发布时间】:2014-04-07 06:09:49
【问题描述】:

我尝试用完整的图像 url 替换所有不包含完整 url 的 img src

这样的例子

<?php
$html_str = "<html>
            <body>
                Hi, this is the first image
                    <img src='image/example.jpg' />
                this is the second image
                    <img src='http://sciencelakes.com/data_images/out/14/8812836-green-light-abstract.jpg' />
                and this is the last image
                    <img src='image/last.png' />
            </body>
        </html>";

?>

当替换变成这样的时候

 <?php
 $html_str = "<html>
            <body>
                Hi, this is the first image
                    <img src='http://example.com/image/example.jpg' />
                this is the second image
                    <img src='http://sciencelakes.com/data_images/out/14/8812836-green-light-abstract.jpg' />
                and this is the last image
                    <img src='http://example.com/image/last.png' />
            </body>
        </html>";

 ?>

那么如何检查每个不是完整链接的img src并替换它? ($html_str 是基于 mysql 的动态)

请给我一些解决这个问题的方法

谢谢

【问题讨论】:

    标签: php mysql image preg-replace


    【解决方案1】:

    我会正确使用 DOM 库,例如

    $doc = new DOMDocument();
    $doc->loadHTML($html_str);
    
    $xp = new DOMXPath($doc);
    $images = $xp->query('//img[not(starts-with(@src, "http:") or starts-with(@src, "https:") or starts-with(@src, "data:"))]');
    foreach ($images as $img) {
        $img->setAttribute('src',
            'http://example.com/' . ltrim($img->getAttribute('src'), '/'));
    }
    $html = $doc->saveHTML($doc->documentElement);
    

    在这里演示 - http://ideone.com/4K9pyD

    【讨论】:

      【解决方案2】:

      试试这个:

      您可以使用以下代码获取图像源:

      $xpath = new DOMXPath(@DOMDocument::loadHTML($html));
      $src = $xpath->evaluate("string(//img/@src)");
      

      之后检查字符串是否包含http。根据做操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多