When building custom functionality into WordPress, it’s important to make sure that you’re properly sanitizing data. WordPress provides an array of utility functions for doing this.

But there are times when completely sanitizing the input may be too much. For example, say you’re working on a widget that has a text field and you’re comfortable with allowing the user to input styles and markup but want to remove any JavaScript. Using strip_tags and strip_slashes is overkill, obviously. These would reduce the input into nothing but the raw text.

Here’s a simple way to removing JavaScript tags from input fields while still supporting inline CSS and HTML markup:

Say we’re working with a widget and the user wants to provide text that looks like this:

<script type="text/javascript">alert('Hello world!');</script><strong>Hi There!</strong><p>My name is Tom.</p>

And we want the end result to look like this:

<strong>Hi There!</strong><p>My name is Tom.</p>

A simple regular expression will allow you to parse out the script tags (and it accounts for new lines, too):

preg_replace( '/<scriptb[^>]*>(.*?)</script>/is', '', $input );

Practically speaking, here’s a gist of what the update function may look like:

A word of caution: This way is suitable for smaller cases, but I don’t recommend this for trying to sanitize data for larger fields or larger systems.