2017-07-17 50 views
0

用的preg_replace我要修改所有出现的内嵌JavaScript(script标签内)HTML页面上,如果脚本包含“jQuery的”,它不含'推迟'。修改是在现有脚本周围添加额外的脚本。添加代码,如果脚本包含了preg_replace某些字符串

因此,举例来说,这是(部分)的HTML输出:

<script type="text/javascript">//Should not match, because of 'defer' 
    function defer(method) { 
     if (window.jQuery) { 
      method(); 
     } else { 
      setTimeout(function() { defer(method) }, 50); 
     } 
    } 
</script> 

<script type="text/javascript">//Should match because of 'jQuery' 
    jQuery(document).ready(function(){ 
     //some code 
    }); 
</script> 

<script type="text/javascript">//Should not match, because of no 'jQuery' 
    window._wpemojiSettings = {"baseUrl"....."} 
</script> 

<script type="text/javascript">//Should match because of 'jQuery' further down within the script tag 
    if(typeof gf_global == 'undefined') //some other code 
    jQuery(document).bind(function(){ 
     //some code 
    }); 
</script> 

现在我已经来到这个:

$buffer = preg_replace('#<script type="text\/javascript">(.*?jQuery.*?)<\/script>#is', '<script type="text/javascript">/*Additional code around it*/$1/*Additional code*/</script>', $buffer); 

然而,当jQuery的不脚本内发生标签,其余的HTML也被考虑在内,直到'jQuery .../script>'出现。

对此的任何想法?

非常感谢!

回答

0

这个怎么样的解决方案(它的测试):

$html_segment = "your html part with multiple script tags"; 
$insert_before ="<script to put BEFORE><br/>"; 
$insert_after = "<br/><script to put AFTER>"; 
$avoid_tag = "defer"; 
$search_tag ="jQuery"; 
// 
$temp = explode("<script", $html_segment); 
$result = ""; 
$len = count($temp); 
for ($i=0; $i<$len; $i++) { 
    $part = $temp[$i]; 
    // check if this part contains 'jQuery' 
    // and does NOT contain 'defer' 
    // if not -> do something 
    if (strpos($part, $search_tag) !== false && 
     strpos($part, $avoid_tag) === false) { 
    // change 
    $part = $insert_before."<script".$part; 
    $part = str_replace("</script>", "</script>$insert_after", $part); 
    } else if ($i >0) { 
    // put back the original 
    $part = "<script".$part; 
    } 
    $result.=$part; 
} 
//END: $result now has the new HTML 
// proof: 
echo "<textarea>$result</textarea>"; 
// 
+0

该解决方案的伟大工程!感谢您的回答。 – Jeroendebeurs

+0

很高兴听到这个:)它不是正则表达式,但你可以很容易地适应其他用途。 – verjas