Wednesday, 20 June 2012

Strip All Non Alphanumeric Characters


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
      
    $string '(1234) S*m@#ith S)&+*t `E}{xam)ple?>land 1!_2)#3';
    echo alphanumericAndSpace$string ); 
?>

Output
 
1234 Smith St Exampleland 123

No comments:

Post a Comment