【问题标题】:Add code within script tags if script contains certain string with preg_replace如果脚本包含带有 preg_replace 的特定字符串,则在脚本标签中添加代码
【发布时间】:2017-07-17 14:11:26
【问题描述】:

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

例如,这是 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>'。

对此有什么想法吗?

提前非常感谢!

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

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

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

    【讨论】:

    • 很高兴听到这个 :) 它不是正则表达式,但您可以轻松地将其调整为其他用途。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2015-01-26
    • 2016-09-16
    • 2012-09-03
    相关资源
    最近更新 更多