Skip to main content

PHP function to Remove Non AlphaNumeric Characters from a given string with exclusion list


PHP provides various pattern matching regular expression functions as well as string functions to perform this task.

PHP built-in functions for this are str_replace, str_ireplace, preg_replace, substr_replace ,preg_match

It is recommended to use PHP string replace functions over regex functions to do simple string replace functions.There is nothing wrong with using a regex , regular expressions have to be compiled and strings to be parsed, but some people wrongly them by doing silly things like :
preg_match('/txt/', $str) instead of strpos('txt', $str) !== false      OR
preg_replace("/txt/", "", $str) instead of str_replace('txt', $str)



Using Regular expression PREG_REPLACE Function

PREG_REPLACE is the php built in function to check for a particular string pattern and replace with another one. It performs a regular expression search and replace.

function removeNonAlphanumericChars($str){
return preg_replace("/[^a-zA-Z0-9]/", "", $str);
}


Usage:
$str="%#&&&^&jsdfj%*&%*_^^.pp09==-is9";
echo( removeNonAlphanumericChars($str) );


Or simply
$str="%#&&&^&jsdfj%*&%*_^^.pp09==-is9";
echo( preg_replace("/[^a-zA-Z0-9]/", "", $str));


the "0-9" in the pattern can be replaced with "\d" and the function looks like:
$str="%#&&&^&jsdfj%*&%*_^^.pp09==-is9";
$new_str = preg_replace("/[^a-zA-Z\d]/", "", $str);



Exlusion of Characters from replacement

PHP allows exclusion of characters, if you want to replace all non AlphaNumeric character except dot (.), Hyphen (-) and underscore (_) you can do it like this:

$str="%#&&&^&jsdfj%*&%*_^^.pp09==-is9";
$new_str = preg_replace("/[^a-zA-Z0-9\.\-_]/", "", $str);


The above function will remove all characters which are not small letter alphabets (a-z), capital letter alphabets (A-Z), dot (.), Hyphen (-) and underscore (_).

You can find a backslash (\) before dot and Hyphen. This is because "." and "-" are used as Quantifiers while writing regular expression patterns. So while adding a backslash before those characters will treat them as a string.



Alternative Non Alphanumeric Character function using simple PHP in_array and str_replace functions

Simple PHP function with our reular expression to remove all Non Alphanumeric Characters ina string:

Here there is an array of allowed character "$allowedCharacters". function will loop through the characters in the string and check the presence of character in the array. The characters which are not in the array are replace by "@" character. Later "@" is replace by "" and you will get a Non Alphanumeric Character replaced string.

function removeNonAlphanumericChars($str){

$allowedCharacters = array (
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'
);

for($i = 0; $i < strlen($str); $i++) {
if (! in_array(strtolower($str[$i]), $allowedCharacters)) {
$str[$i] = '@';
}
}
return str_replace('@', '', $str);
}


$str="%#&&&^&jsdfj%*&%*_^^.pp09==-is9";
echo( removeNonAlphanumericChars($str) );




You can also add exclusions in $allowedCharacters array. Function looks like this:

function removeNonAlphanumericCharsWithExclusions($str){

$allowedCharacters = array (
'.', '-', '_', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'
);

for($i = 0; $i < strlen($str); $i++) {
if (! in_array(strtolower($str[$i]), $allowedCharacters)) {
$str[$i] = '@';
}
}
return str_replace('@', '', $str);
}

$str="%#&&&^&jsdfj%*&%*_^^.pp09==-is9";
echo( removeNonAlphanumericCharsWithExclusions($str) );



Hope this helps :)

Popular posts from this blog

Strange problem occured while trying to create a CSV file using PHP Script - The file is not seen on FTP but can download using file's absolute path url

Strange problem occured while trying to create a CSV file - The file is not seen on FTP but can download using file's absolute path url Last day I came across a strange problem when I tried to create a csv file on therver using a PHP script. the script was simply writing a given content as a csv file. The file will be created runtime. What happened was, The script executed fine, file handler for new file was created and contents was wrote into the file using fwrite and it returned the number of bytes that was written.

How to get the Query string of a URL using the Javascript (JS)?

JS function get the Query string of a URL or value of each parameter using the Javascript(JS)? If you want to get your current page's url var my_url=document.location; to get the query string part of the url use like this: var my_qry_str= location.search; this will return the part of the url starting from "?" following by query string Lets assume that your current page url is http://www.crozoom.com/2013/page.html?qry1=A&qry2=B then the location.search function will return " ?qry1=A&qry2=B " to exclue "?", do like this:


Urgent Openings for PHP trainees, Andriod / IOS developers and PHP developers in Kochi Trivandrum Calicut and Bangalore. Please Send Your updated resumes to recruit.vo@gmail.com   Read more »
Member
Search This Blog