regex - Remove all hyphens, special characters etc. from string in PHP

853

Is there a general used regex that removes ALL hyphens, special characters etc., so I will only get letters.

For example a regex containing: ,./<>?;':"|[]{}[email protected]#$%^&*()|\ ~` and all of the hyphens and special characters.

(don't know if this is called a regex, but I hope you get the idea)

191

Answer

Solution:

This should work :

$string = preg_replace("/[^a-zA-Z]+/", "", $string);

if you want to keep numbers, use this one :

$string = preg_replace("/[^a-zA-Z0-9]+/", "", $string);
985

Answer

Solution:

If you need to get only letters, remove all that are not letters:

preg_replace('~\P{L}+~u', '', $input)

The\P{L} is a Unicode property that matches all characters other than Unicode letters. See the regex demo.

If you need to also handle diacritics (i.e. if you need to keep them), use

preg_replace('~[^\p{M}\p{L}]+~u', '', $input)

where\p{M} matches any diacritic symbol, and[^\p{M}\p{L}]+ matches 1 or more characters other than letters and diacritics.

See another demo.

People are also looking for solutions to the problem: php - How to store and sometimes update a global variable in Silex

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.