这是我的内容:
<p><img src="http://localhost/contents/uploads/2017/11/1.jpg" width="215" height="1515"></p>
这是我的 PHP 代码:
function convert_the_content($content){
$content = preg_replace('/<p><img.+src=[\'"]([^\'"]+)[\'"].*>/i', "<p class=\"uploaded-img\"><img class=\"lazy-load\" data-src=\"$1\" /></p>", $content);
return $content;
}
我使用我的代码为<p>
标签和<img>
标签添加一个类并转换src=""
为data-src=""
.
我的代码从<img>
标签中删除了宽度和高度属性的问题,所以我的问题是如何更改我的代码以使其工作并获取这些详细信息?
注意:我的内容可能有很多<img>
和<p>
标签。
如果你只有这个非常精确的 HTML 片段,你可以通过这样做更简单
$html = <<< HTML
<p><img src="http://localhost/contents/uploads/2017/11/1.jpg" width="215" height="1515"></p>
HTML;
$html = str_replace('<p>', '<p class="foo">', $html);
$html = str_replace(' src=', ' data-src=', $html);
echo $html;
这将输出
<p class="foo"><img data-src="http://localhost/contents/uploads/2017/11/1.jpg" width="215" height="1515"></p>
如果您尝试转换任意 HTML,请考虑使用 DOM 解析器:
<?php
$html = <<< HTML
<html>
<body>
<p><img src="http://localhost/contents/uploads/2017/11/1.jpg" width="215" height="1515"></p>
<p><img width="215" height="1515" src="http://localhost/contents/uploads/2017/11/1.png"></p>
<p ><img
class="blah"
height="1515"
width="215"
src="http://localhost/contents/uploads/2017/11/1.png"
>
</p>
</body>
</html>
HTML;
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_use_internal_errors(false);
$xpath = new DOMXPath($dom);
foreach ($xpath->evaluate('//p[img]') as $paragraphWithImage) {
$paragraphWithImage->setAttribute('class', 'foo');
foreach ($paragraphWithImage->getElementsByTagName('img') as $image) {
$image->setAttribute('class', trim('bar ' . $image->getAttribute('class')));
$image->setAttribute('data-src', $image->getAttribute('src'));
$image->removeAttribute('src');
}
};
echo $dom->saveHTML($dom->documentElement);
输出:
<html><body>
<p class="foo"><img width="215" height="1515" class="bar" data-src="http://localhost/contents/uploads/2017/11/1.jpg"></p>
<p class="foo"><img width="215" height="1515" class="bar" data-src="http://localhost/contents/uploads/2017/11/1.png"></p>
<p class="foo"><img class="bar blah" height="1515" width="215" data-src="http://localhost/contents/uploads/2017/11/1.png"></p>
</body></html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句