如果脚本包含带有 preg_replace 的特定字符串,则在脚本标签内添加代码

Add code within script tags if script contains certain string with preg_replace

使用 preg_replace 如果脚本 包含 'jQuery',我想修改 HTML 页面上所有发生的内联 javascript(在脚本标记内) 并且 不包含 'defer'。修改是在现有脚本周围添加额外的脚本。

例如,这是 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*//*Additional code*/</script>', $buffer);

然而,当 jQuery 没有出现在脚本标签中时,其余的 HTML 也会被考虑在内,直到出现 'jQuery.../script>'。

对此有什么想法吗?

非常感谢!

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

$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>";
//