Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP remove symbols from string

Tags:

Searching through the internet and this website as well, I've found several topics on the matter. Thing is, there are countless solutions if the inserted strings must contain only characters of the Latin alphabet, but when the case requires text of other alphabets it gets a bit tricky.

Is there any way I can strip in PHP all symbols from a string, but leave the actual letters of all UTF-8 alphabets? I have tried already creating an array of all the characters of my keyboard and then by using str_replace or preg_replace remove them, but then I found out that different countries have also different keyboards sometimes which include different symbols. For example, my qwerty keyboard doesn't have the £ symbol, which a British keyboard might have.

I know this is a weird question, I am just wondering if there is an easy solution to it which I may have missed.

Any help would be very much appreciated!

EDIT: OK After some better and extended Google-ing I have found out that the following regular expression works fine for what I need and it keeps all letters of all types of alphabets while removes all symbols. I am sharing it here in case somebody else would need to do the same.

$string = preg_replace('/[^\p{L}\p{N}\s]/u', '', $string);

like image 517
Dimitris Damilos Avatar asked May 24 '13 11:05

Dimitris Damilos


People also ask

Why trim () function is used in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string.

How remove all special characters from a string in PHP?

One useful function that can be used to remove special characters from a string is the str_replace() function. The empty string must be used to the replace character in this function to remove the specified character. The syntax of this function is given below. The str_replace() function can take four arguments.


1 Answers

The solution is this: $string = preg_replace('/[^\p{L}\p{N}\s]/u', '', $string);

like image 162
Dimitris Damilos Avatar answered Oct 21 '22 01:10

Dimitris Damilos