Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything except letters from PHP string

How can I remove everything from a string apart from letters? I have an input field for first names.

like image 668
frankmeacey Avatar asked Aug 31 '11 22:08

frankmeacey


People also ask

How can I get only letters from string in PHP?

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s); If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes. Try this to leave only A-Z: $result = preg_replace("/[^A-Z]+/", "", $s);

How to remove junk characters from string in PHP?

Using str_replace() Method: The str_replace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).


2 Answers

In PHP, you can use (as suggested by @rczajka and @mario):

preg_replace('/\PL/u', '', $str)

Working Example: http://codepad.viper-7.com/V78skl

You may want to checkout this Tutorial for regex

like image 158
Martin Schlagnitweit Avatar answered Sep 23 '22 23:09

Martin Schlagnitweit


$new_string = preg_replace('/[^a-z]/i','',$old_string);
like image 28
Brian Glaz Avatar answered Sep 19 '22 23:09

Brian Glaz