在str_replace函数中修复未定义的变量和Array到字符串的转换

时间:2017-03-14 20:55:28

标签: php arrays regex string str-replace

我有这个功能:

// load styles asynchronously - Transform stylesheet markup to loadCSS compatible
add_filter( 'style_loader_tag', 'style_transform_loadCSS', 10, 2 );

function style_transform_loadCSS( $html, $handle ) {
    if ( $handle == CHILD_THEME_NAME  )

        $search = array("rel='stylesheet' id='$handle-css'", "type='text/css' media='all'");
        $replace = array("rel=\"preload\"", "as=\"style\" onload=\"this.rel='stylesheet'\"");

    return str_replace($search, $replace, $html)."<noscript>{$html}</noscript>";

}

它正常工作,但在调试时我看到了这个错误:

  

注意:未定义的变量:在第362行的/home3/me/public_html/wp-content/themes/child/functions.php中搜索

     

注意:第362行/home3/me/public_html/wp-content/themes/child/functions.php中的数组到字符串转换

第362行是:

return str_replace($search, $replace, $html)."<noscript>{$html}</noscript>";

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

问题是你错过了一些括号。在您的示例中,您的语句仅转到下一行,这是您的$search变量。如果您的陈述为false,则您的变量未定义,并且您在替换字符串的下一行中会遇到一些问题。

function style_transform_loadCSS( $html, $handle ) {
    if ($handle == CHILD_THEME_NAME) {
        $search = array("rel='stylesheet' id='$handle-css'", "type='text/css' media='all'");
        $replace = array("rel=\"preload\"", "as=\"style\" onload=\"this.rel='stylesheet'\"");
        $html = str_replace($search, $replace, $html)."<noscript>{$html}</noscript>"
    }
    return $html;
}
相关问题