Strip All Non Alphanumeric Characters Except Space With PHP

A quite common request received is to strip all “bad characters” except for a space. Bad characters are defined in these requests as any non alpha numeric characters. Most often these requests are from people who wish to sanitize postal addresses or the like. This simple function provides a basic wrapper for the PHP function preg_match to strip out the unwanted characters and returns a sanitized string, including white space characters.

<?php
/**
* Remove all non alpha numeric characters except a space
*
* @param    string    $string The string to cleanse
*
* @return    string
*
*/
function alphanumericAndSpace( $string )
{
return
preg_replace('/[^a-zA-Z0-9\s]/', '', $string);
}
?>

Note that in the example function above, the \s modifier is used to capture the space. This will also capture newline characters also.

Example

<?php
/** a string with some "bad characters" ***/
$string = '(1234) S*m@#ith S)&+*t `E}{xam)ple?>land 1!_2)#3)(*4""5';

/*** call the function and strip the bad characters ***/
echo alphanumericAndSpace( $string );
?>

Demonstration

1234 Smith St Exampleland 12345

Advertisements