Ad

Use PHP To Find And Remove Some Javascript Tag But Leave Another Tag

i have html containt some googletag like this :

<script type='text/javascript'>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
</script>

<script type='text/javascript'>
googletag.cmd.push(function() {
  googletag.defineSlot('/6176201/Opera_120x600', [120, 600], 'div-gpt-ad-6176201-opera_120x600').addService(googletag.pubads());
  googletag.defineSlot('/6176201/Opera_300x250', [300, 250], 'div-gpt-ad-6176201-opera_300x250').addService(googletag.pubads());
  googletag.defineSlot('/6176201/Opera_728x90', [728, 90], 'div-gpt-ad-6176201-opera_728x90').addService(googletag.pubads());
  googletag.defineSlot('/6176201/Contextuals_Operaweb', [557, 30], 'div-gpt-ad-6176201-contextuals_operaweb').addService(googletag.pubads());
  googletag.pubads().collapseEmptyDivs();
  googletag.pubads().enableSingleRequest();
  googletag.enableServices();
});
</script>

<script type='text/javascript'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-6176201-opera_728x90'); });
</script>

<script type='text/javascript'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-6176201-opera_120x600'); });
</script>

<script type='text/javascript'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-6176201-opera_300x250'); });
</script>

It place random in html code, i want to find and remove it but do not touch another script tag like google analytics, etc. Just do Google search and look in to a lot of answer but still don't know how to do. Please help.

Ad

Answer

Try this one regex:

/<script type='text\/javascript'(?:(?!<\/?script).\n)+?(\n*.*?)*?(googletag)(\n*.*?)*(?:(?!<\/?script>))*?<\/script>/gi

Test it online

Ad
source: stackoverflow.com
Ad