他的内容是
<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_replcae:
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));
}
答案 0 :(得分: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,但我不建议您这样做,因为它将来可能会让您无语。