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

How to apply for a new ration card and what are the documents required?

List of documents required for new ration card application in Kerala and how to apply


Application for a new ration card should be addressed to Taluk Supply Officer (TSO) / City Rationing Officer (CRO) of applicant's residing area.

Primary document required are Residence certificate, Income certificate and incase the applicant's name is in another ration card then he/she should submit the reduction certificate ontained from previous TSO / CRO as proof for removing his/her name from old Ration card.

You can get the new application from your currently residing Taluk Supply Office.

Payback Points - How to redeem - How to merge multiple payback accounts - Block Payback card - Payback customer care

Joomla and Forum Integration - Integrating Forums to Joomla

Joomla is one of the most popular CMS opensource packages. It is very easier to develop website's using Joomla. You just need to download Joomla package from Joomla's Official website www.joomla.org  and install it on your domain and later adding customizations to templates and feature and Your website is ready :). Now a days most websites provides a forum section for it users for discussing various article topics, gathering opinions etc.



Following are some best know forum opensource packages which can be integrated with Joomla and create a new forum experience for users


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