.Maui Blog

Remove script tags from string with PHP

Remove script tags (or other types of tags) from a string in PHP is really easy, here’s how:

<?php
$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.dotmaui.com/dotmaui/css/dark.css" />
<script>
alert('1')
</script>
<script type="text/javscript">
alert('1')
</script>
</head>
<body>
<p>My paragraph.</p>
<script id="sambucajs" src="https://cdn.dotmaui.com/dotmaui/js/sambuca-0.1.5.min.js" async></script>
</body>
</html>
HTML;

$html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);

echo $html;

Result:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.dotmaui.com/dotmaui/css/dark.css"/>
</head>
<body>
<p>My paragraph.</p>
</body>
</html>
Exit mobile version