How To Strip All Non-Alphabetic Characters From A String?
Add a comment
November 3rd, 2009
String manipulation is the common thing to do with web application development. It is very easy to get it done when you are having a complete library to deal with it. PHP has a very vast support on string manipulation and has many functions including regular expressions support.
Sometimes you may need to work with user inputs to get only the alphabets. I searched a lot on google but didn’t find a suitable example to get it done. So I spent time, re-searched on net and created an example for myself and to share with you all. Hope it saves time for you in your development.
Here is the code beauty: I created a function, so that you can simply re-use it without any further modifications.
<?php //the text before, we usually get it from user input $string = 'Remove all non-alphabetic characters: äósa Sachin9Kumar %^$2423Raj#*8put'; //prints the text before echo 'Before: ' . $string . '<br />'; //prints the result string with having only alphabets echo 'After: ' . allowAlphabets($string); //It will return: Remove all non alphabetic characters sa Sachin Kumar Raj put //@description: replace all non-alphabets characters from the given string. //@return : result string or false function allowAlphabets($string){ //create an array which has only allowed characters set $allow_characters=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','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'); //start of regx pattern $pattern = "@[^("; //generate a regx pattern foreach ($allow_characters as $char) { $pattern .= preg_quote($char, "@"); } //close the regx pattern string $pattern .= ")]@"; //replace all non alphabets characters with space $after = preg_replace($pattern, " ", $string); //prints the result string with having only alphabets return $after; } ?>
About The Author









Recent Comments