How to remove unwanted characters from a string in PHP?

I am trying to save post links from titles. But the problem is, there could be a lot of unwanted characters for example "! * # + &" and many more. So how can I remove them? I just want to keep a-z letters and 0-9 numbers.

You can easily solve this problem with PHP preg_replace() function. All you need is regex to remove unwanted characters. Or you can say keep only selected characters and remove everything else.
Let’s try to understand a few regex.

If you want to select all the characters other than letters (the lowercase letters “a-z”, and the uppercase letters “A-Z”):


And If you want to include numbers here then the regex should like this.


For your case, you may not need white space but still, I am just explaining it here so others can use it.


So now the final part, Use the regex in preg_replace() and you will get your expected result.

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