首页 > 解决方案 > PHP-Diff 跳过脚本标签

问题描述

我目前正在使用https://github.com/rashid2538/php-htmldiff来区分两个 html 页面,但问题是<script></script>标签中的内容也有差异,我不想这样做,因为它破坏了可运行性。我查看了代码,但我不知道在哪里进行调整以忽略脚本标签,因为我只是开始使用 php 作为我的第一语言。我了解代码的解析原理,但其他一切对我来说都很神秘。

有人可以就改变什么提供建议或提示吗?

文件1:

<html>
    <head>
       <script> var thing = 'test'; </script>
    </head>
    <body>
    </body>
</html>

文件2:

<html>
    <head>
       <script> var thing = 'anothertest'; </script>
    </head>
    <body>
    </body>
</html>

结果:

<html>
    <head>
       <script> var thing = '<del class="diffmod">test</del><ins class="diffmod">anothertest</ins>'; </script>
    </head>
    <body>
    </body>
</html>

标签: javascriptphphtml

解决方案


您可以使用regex从两个html字符串中查找脚本标签,然后使用preg_replace()删除它们。之后,将两个字符串与htmldiff函数一起使用

$regex = '/<script\b[^>]*>(.*?)<\/script>/i';
$html1_parsed = preg_replace($regex, '', $html1);
$html2_parsed = preg_replace($regex, '', $html2);

推荐阅读