我想要的是一个可以根据用户输入运行的函数,该函数将智能地查找并添加width
and height
任何属性<img>
HTML blob 中的标记,以避免图像加载时的页面重排问题。
我正在为 PHP 论坛编写发布脚本,其中用户的输入在写入数据库以供以后显示之前经过清理并且通常变得更好。作为我如何让事情变得更好的一个例子,我有一个脚本插入alt
属性到图像中,如下所示:
Here are two images: <img src="http://example.com/image.png"> <img src="http://example.com/image2.png">
经过发布脚本的清理后,变成
Here are two images: <img src="http://example.com/image.png" alt="Posted image"> <img src="http://example.com/image2.png" alt="Posted image">
(这使得它在严格的 HTML 4 下验证,但可能不符合 alt 属性的精神 — 唉!)
因此,对于我的功能,我有一个模糊的想法,服务器需要运行getimagesize()
在 HTML 块中找到的每个外部图像上,然后将函数生成的属性应用于每个外部图像<img>
它遇到的标签。我假设这个函数以前已经写过,但我在 Google 或 php.net 文档上没有运气。我是否必须从头开始,或者有人知道我可以使用或适应完成这项工作的(相对)强大的功能吗?
你说得对getimagesize()
。你可以简单地做这样的事情:
$img = 'image2.png';
$info = getimagesize($img);
printf('<img src="%s" %s>', $img, $info[3]);
如果图像托管在远程位置,则您必须下载所有图像(该函数会处理它),因此您可能需要缓存结果以加快后续请求的速度。
Edit:刚刚看到你有一个包含各种的字符串<img>
元素。这应该可以解决问题:
<?php
$html = <<<EOF
something <img src="https://www.google.com/images/logos/ssl_logo_lg.gif"> hello <img src="https://mail.google.com/mail/images/2/5/logo1.png">
EOF;
$dom = new DOMDocument();
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('img') as $img) {
list($width, $height) = getimagesize($img->getAttribute('src'));
$img->setAttribute('width', $width);
$img->setAttribute('height', $height);
}
$xpath = new DOMXpath($dom);
$newDom = new DOMDocument();
foreach ($xpath->query('//body/p')->item(0)->childNodes as $node) {
$newDom->appendChild($newDom->importNode($node, true));
}
$newHtml = $newDom->saveHTML();
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)