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 delete videos from your Youtube Watch History list?

How to Delete Individual or all videos from your Youtube Watch History list? Youtube keeps a fine record of the videos that you had watched earlier. You can view this by visiting the History section. If you want to remove the video's from the list do the following: Logon to Youtube and click on the "History" tab on the left menu to view Watch History ( Read more ) There will be check boxes corresponding to each video in the list Tick the check boxes of the videos which you want to remove Click on " Remove " button to delete the videos.

ICICI prudential Customer portal updated - Option to change password is missing - Know how to change your ICICI prudential password

Recently I received an SMS from ICICI prudential asking for login to their website's customer portal using the phone number as user Id and an autogenerated one time password given in the message as password. The SMS messsage was like this. Dear ***Cust Name*** login to your policy(ies) on www.iciciprulife.com with your user id as **mobile number*** and One time use password as ***password***

What are the Income Tax Rates for Indian citizens for Financial Year 2017-2018?

Income Tax Slab and Rates given below are for Indian citizens of age less than 60. This rates are applicable for the Financial Year 2017-2018 Income Tax Slab Rates Financial Year 2017-2018 Assessment Year 2018-19 Income Tax Slab Rates SLAB 1 Individuals whose total income not exceeding Rs. 2,50,000 ( 2.5 lakhs ) They are exempted from paying income tax.


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