【问题标题】:regex to isolate javascript using preg_replace_callback正则表达式使用 preg_replace_callback 隔离 javascript
【发布时间】:2022-11-14 23:24:12
【问题描述】:

我的 [php executed] 正则表达式很糟糕,我正在努力尝试在 HTML 块中隔离 javascript 脚本。我有以下正则表达式可以部分工作,但是如果文本中有“on”这个词(而不是在<标签>中),它就会遇到问题。

$regex = "/<script.*?>.*?<\/script.*?>(*SKIP)(*F)|((\\bon(.*?=)(.*?))(\'|\")(.*?)(\\5))/ism";

$html = preg_replace_callback($regex,
           function ($matches) {
               $mJS = $matches[2] . $matches[5] . myFunction($matches[6]) . $matches[5];
               return $mJS;
           },
           $html);

我认为问题在于 \bon.... 部分需要在被考虑之前被限定在 < tag > 内,但我只是不知道如何。

运行以下测试...

$html= "<div id='content' onClick='abc()'>Lorem On='abc' ipsum on to</div>
<input id='a' type='range'>
<input id='b' type='range'>
<script>abc();</script>";

返回...

<div id='content' onClick='****abc()****'>Lorem On='****abc****' ipsum on to</div>
<input id='****a****' type='range'>
<input id='b' type='range'>
<script>abc();</script>

但我想...

<div id='content' onClick='****abc()****'>Lorem On='abc' ipsum on to</div>
<input id='a' type='range'>
<input id='b' type='range'>
<script>****abc();****</script>

如果你想玩,我有一个沙箱运行它:https://onlinephp.io/c/a43b1

有没有人有什么建议?

【问题讨论】:

  • 你跳过&lt;script...&lt;/script&gt;但我想要...&lt;script&gt;****abc();****&lt;/script&gt;。很难理解,你能澄清或重新检查你想要的输出吗?
  • 顺便提一句。看起来你不需要回调,试试this PHP demo at tio.run - 正则表达式explained at regex101。猜想这就是预期的。
  • 谢谢 BB - 我不是故意跳过 <script>...</script>.... 是的,我确实想要 <script>****abc();****</script>;我认为我确实需要回调,因为一旦我隔离了代码,我实际上需要调用另一个 PHP 函数(我已经调整了上面的代码示例以现在显示它)
  • 嗯,那为什么要用(*SKIP)(*F)呢?看看this regex101 demo
  • 谢谢 BB - 我认为这对我有用。我在onlinephp.io/c/a249d 上放置了一个可用的 php。

标签: php regex


【解决方案1】:

在 Bobble Bubble 的帮助下,我已经能够完成这项工作......

<?php

function myFunction($tx) {
    return "****$tx****";
}

$html= "<div id='content' onClick='abc()'>Lorem On='abc' ipsum on to</div>
<input id='a' type='range'>
<input id='b' type='range'>
<script>abc();</script>";

$regex = "/(<script[^><]*>)(.*?)(</script>)|onw+s*=s*K(?|(")([^"]+)"|(')([^']+)')/ism";

$result = preg_replace_callback($regex,
        function ($matches)  {
            if ( isset($matches[1])) $m1=$matches[1]; else $m1="";
            if ( isset($matches[2])) $m2=$matches[2]; else $m2="";
            if ( isset($matches[3])) $m3=$matches[3]; else $m3="";
            if ( isset($matches[4])) $m4=$matches[4]; else $m4="";
            if ( isset($matches[5])) $m5=$matches[5]; else $m5="";
            $mJS = $m1.$m4 . myFunction($m2.$m5) .$m3.$m4;
            return $mJS;
        },$html);


echo "Result=$result";
echo "

";
?>

有关正在运行的可执行文件,请参阅 https://onlinephp.io/

【讨论】:

猜你喜欢
  • 2011-01-26
  • 2012-06-23
  • 2010-12-26
  • 2014-02-11
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多