【发布时间】: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