将data-mfp-src属性添加到图像标记PHP

问题描述 投票:-1回答:1

他的内容是:

<div class="image">
   <img src="https://www.gravatar.com/avatar/" alt="test" width="50" height="50">
</div>

我想使用preg_replace添加data-mfp-src属性(从src属性获取值)为最终代码,如下所示:

<div class="image">
   <img src="https://www.gravatar.com/avatar/" data-mfp-src="https://www.gravatar.com/avatar/" alt="test" width="50" height="50">
</div>

这是我的代码,它没有任何问题,但我想使用preg_replace由于某些特定的原因:

function lazyload_images( $content ){
    $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");

    $dom = new DOMDocument;
    libxml_use_internal_errors(true);
    @$dom->loadHTML($content);
    libxml_use_internal_errors(false);

    $xpath = new DOMXPath($dom);
    foreach ($xpath->evaluate('//div[img]') as $paragraphWithImage) {
        //$paragraphWithImage->setAttribute('class', 'test');
        foreach ($paragraphWithImage->getElementsByTagName('img') as $image) {
            $image->setAttribute('data-mfp-src', $image->getAttribute('src'));
            $image->removeAttribute('src');
        }
    };

    return preg_replace('~<(?:!DOCTYPE|/?(?:html|head|body))[^>]*>\s*~i', '', $dom->saveHTML($dom->documentElement));
}
php xpath preg-replace domdocument attr
1个回答
1
投票

作为隔离src值并将新属性设置为此值的有力方法,我将敦促您避免使用正则表达式。并不是说它无法完成,但如果更多的类被添加到<div>,或者<img>属性被转移,我的片段将不会中断。

代码:(Demo

$html = <<<HTML
<div class="image">
   <img src="https://www.gravatar.com/avatar/" alt="test" width="50" height="50">
</div>
HTML;

$dom = new DOMDocument; 
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
// using a loop in case there are multiple occurrences
foreach ($xpath->query("//div[contains(@class, 'image')]/img") as $node) {
    $node->setAttribute('data-mfp-src', $node->getAttribute('src'));
}
echo $dom->saveHTML();

输出:

<div class="image">
   <img src="https://www.gravatar.com/avatar/" alt="test" width="50" height="50" data-mfp-src="https://www.gravatar.com/avatar/">
</div>

资源:


只是为了向您展示正则表达式可能是什么样的......

发现:~<img src="([^"]*)"~

替换:<img src="$1" data-mfp-src="$1"

演示:https://regex101.com/r/lXIoFw/1但是我不推荐它,因为它可能会在未来默默地让你失望。

© www.soinside.com 2019 - 2024. All rights reserved.