php preg_replace kills cpu I am reading some HTML files and returning them upon request, but when they go through my codes I need to filter out some stuff from these HTMLs, everything is working fine and I'm using about 20 or more str_replace and preg_replace to do that which works pretty fine.

Until I used this

$responseBody = preg_replace('/&lt;script&gt;((?!&lt;)[\s\S])*googletagmanager\.com[\s\S]*?&lt;\/script&gt;/', '', $responseBody);


which is supposed to remove this part from html

&lt;script&gt;
(function (w, d, s, l, i) {
    w[l] = w[l] || []; w[l].push({
        'gtm.start':
        new Date().getTime(), event: 'gtm.js'
    }); var f = d.getElementsByTagName(s)[0],
    j = d.createElement(s), dl = l != 'dataLayer' ? '&amp;l=' + l : ''; j.async = true; j.src =
    '//www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM');&lt;/script&gt;


and it does that very well in a regex tester => http://regexr.com/3e8nb
but on the server cpu just goes up and the server halts. 
why is this happening? and how can I improve this regex?
Simple as that:

/&lt;script&gt;[^&lt;]*?googletagmanager\.com.*?&lt;\/script&gt;/s


What's killing performance for you, is most likely the backtracking followed by a look-ahead on the first padding. Using a character class instead of a look-ahead, and making it non-greedy should solve that issue.

The /s modifier allows you to use . instead of explicit [\s\S].