【问题标题】:How to add image dimensions in an image being added via regex如何在通过正则表达式添加的图像中添加图像尺寸
【发布时间】:2015-05-25 14:54:07
【问题描述】:

这是来自 WordPress 插件的一段 PHP 代码,它使用 preg_replace 将图像添加到内容中。问题是添加的图像没有指定尺寸,并且由于在每个页面上多次添加此图像,它会减慢页面渲染速度(在很小程度上)。现在,问题是:

如何在通过下面提到的 PHP 正则表达式添加的图像的最终 HTML 中添加宽度 = "1" 和高度 = "1"?

 // In case you want to change the placeholder image
        $placeholder_image = apply_filters( 'lazyload_images_placeholder_image', self::get_url( 'images/1x1.trans.gif' ) );


    // This is a pretty simple regex, but it works
        $content = preg_replace( '#<img([^>]+?)src=[\'"]?([^\'"\s>]+)[\'"]?([^>]*)>#', sprintf( '<img${1}src="%s" data-lazy-src="${2}"${3}><noscript><img${1}src="${2}"${3}></noscript>', $placeholder_image ), $content );
        return $content;

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: php html regex wordpress


    【解决方案1】:

    如果它们都没有设置尺寸,您可以简单地将width="1" height="1" 添加到 img 标签。

    像这样:

    $content = preg_replace( '#<img([^>]+?)src=[\'"]?([^\'"\s>]+)[\'"]?([^>]*?)(\/)?>#', sprintf( '<img${1}src="%s" data-lazy-src="${2}"${3} width="1" height="1" /><noscript><img${1}src="${2}"${3}></noscript>', $placeholder_image ), $content );
    

    如果添加在&lt;img&gt; 标签的末尾,即使原始图像已经设置了它也不应该干扰。

    【讨论】:

    • 虽然它添加了高度和宽度属性,但我在 W3C 验证器上收到了这些错误:斜杠没有紧跟 >。 …t="关于哈利波特的有趣事实" / width="1" height="1"> ...... 重复的属性宽度。 …t="关于哈利波特的有趣事实" / width="1" height="1"> ......重复的属性高度。 …t="关于哈利波特的有趣事实" / width="1" height="1">
    • 我已经修改了代码来处理这个斜线。应该工作。
    • 它仍然无法正常工作,因为我现在收到此错误:斜线没有紧跟 >...."关于哈利波特的有趣事实" / width="1" height="1" /> ..... 重复的属性宽度。 …“关于哈利波特的有趣事实”/width="1" height="1" /> .......... 重复属性高度。 …“关于哈利波特的有趣事实”/width="1" height="1" />
    • 抱歉,周末没时间测试。另一个编辑,现已测试:)
    猜你喜欢
    • 2014-06-07
    • 2011-05-26
    • 1970-01-01
    • 2013-04-02
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    相关资源
    最近更新 更多