Tuesday, June 15, 2010

Rip Javascript in PHP with a str_replace()

So yesterday, I gave a nod to David Baker's preg_match across multiple lines. And now, the reason I was looking for something along that route, tada!



function rip_java($content) {
$p = '|(\<script.+?\>.+?\</script\>)|ms';
preg_match_all($p, $content, $matches);
if ($matches[0]) {
foreach ($matches[0] as $v) {
$gp = '|http://drincruz\.blogspot\.com|i';
preg_match($gp, $v, $gpmatches);
if (!$gpmatches) {
$content = str_replace($v, '', $content);
}
}
}
return $content;
}


Javascript is very useful in this revision of the internet. However, if you allow other people's javascript on your site, then well, that's an entire whole different security issue. So what we wanted to do at work was only allow certain javascript to run on our sites; and that javascript being the code that we write.

This was written in PHP because we're using it with WordPress' content_save_pre filter.

Cheers!

No comments: