NickStallman.net

Strip all but certain characters from a string in PHP (such as alphanumeric, numeric, etc…)

by on May.09, 2012, under internet

The #1 result in Google for stripping characters out of strings in PHP is awful and uses the deprecated ereg_replace function so lets make a new search result using preg_replace which is much better, faster and it is fully supported in PHP 5.3 and 5.4.

Allow only alphanumeric:

$out = preg_replace('|[^A-Za-z0-9]|', '', $in);

Only numeric:

$out = preg_replace('|[^0-9]|', '', $in);

Alphanumeric with whitespace:

$out = preg_replace('|[^A-Za-z0-9\s]|', '', $in);

The ^ means match everything that is not listed, so you just list anything you need like symbols, numbers and letters and it will match everything else and replace it with nothing leaving you with a nice clean string. You can use this to filter stuff like hexadecimal, base64, postcodes, or just to force plain text.


Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...