1

我想延迟加载背景图片,所以我需要转换

<div class="post-header post-tp-11-header" style="background-image: url(https://cdn.guest.blog/wp-content/uploads/2017/01/A-Beautiful-Message-for-Anyone-Who-is-Searching-For-Love-750x430.jpg);">

<div class="post-header post-tp-11-header" data-original="https://cdn.guest.blog/wp-content/uploads/2017/01/A-Beautiful-Message-for-Anyone-Who-is-Searching-For-Love-750x430.jpg">

[样式可能包含两个或多个属性,只应删除背景图像属性]

我已经使用以下 PHP进行了部分工作,但它仅适用于标签,它不适用于任何div

static function add_background_placeholders( $content ) {
    // Don't lazyload for feeds, previews, mobile
    if( is_feed() || is_preview() || ( function_exists( 'is_mobile' ) && is_mobile() ) )
        return $content;
    // Don't lazy-load if the content has already been run through previously
    if ( false !== strpos( $content, 'data-background' ) )
        return $content;
    preg_match_all('~\bstyle=(\'|")(.*?)background(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\)~i',$content,$matches);

    if( empty( $matches ) ) return $content;

    foreach( $matches[0] as $match ){
         preg_match('~\bbackground(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\)~i',$match,$bg);              
         $bg_less_match = str_replace( $bg[0], '', $match );             
         $data_match = 'data-background="'.$bg['image'].'" '.$bg_less_match;
         $content = str_replace( array($match.';', $match), array( $data_match, $data_match), $content);
    }

  return $content;
}

我已尽力解决但找不到解决方案

[Mods:如果有任何问题,请更正此问题]

4

1 回答 1

1

默认情况下,您问题中的函数实际上会搜索div。我在这里测试过:https ://regex101.com/r/HunEXt/1 。

问题可能是您没有将正确的内容作为参数传递。


另外,请确保您正在更改线路

$data_match = 'data-background="'.$bg['image'].'" '.$bg_less_match;

$data_match = 'data-original="'.$bg['image'].'" '.$bg_less_match;

获取您想要的数据属性。

于 2017-02-08T12:11:56.860 回答