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

Deep-sea Anglerfish Black Seadevil Scary looking creature Video

Deep-sea Anglerfish are the strange and elusive creature that are very rarely observed in their natural habitat. Fewer than half a dozen have ever been captured on film or video by deep-diving research vehicles.They are mostly  found in tropical to temperate waters of the Indian,Pacific and Atlantic Oceans.

How to use WiFi adapter on Ubuntu 16.04 desktop PC - Realtek RTL8188EUS 802.11n Wireless USB Network Adapter Driver installation

Installation of Realtek RTL8188EUS 802.11n Wireless USB Network Adapter on Desktop PC having Ubuntu 16.04 OS My PC is running in Ubuntu 16.04 OS, recently I thought of using a dongle wife adapter to access our home's Wifi network. For this I used Realtek RTL8188EUS 802.11n Wireless USB Network Adapter ( Model No: OT-WUA950NM ) This small device cost around Rupees 250/- to Rs 300/- in India. I did the following steps for installation of this Realtek Nano Wifi Adapter: Plug Realtek RTL8188EUS 802.11n Wireless USB Network Adapter to your PC's USB port, Take the terminal application and run the command "lsusb" to list the plugged in usb devices: Myhome:~$ lsusb Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 001 Device 003: ID 0bda:8179 Realtek Semiconductor Corp. R...

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.


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