PHP: Remove special characters from a string.

This is a guide on how to remove special characters from a string using PHP. In this post, I will provide a number of different examples on how to strip out non-alphanumeric characters.

This can be a useful approach to take if you are dealing with user-inputted data for usernames and post codes, etc.

Remove ALL non-alphanumeric characters.

If you want to remove everything that isn’t a letter or a number, then you can use the following regular expression:

The PHP string above contains an asterisk, a hyphen, an apostrophe, a blank space and two curly brackets. However, if we pass it into preg_replace and remove all non-alphanumeric characters, we are left with the following:

preg_replace

As you can see, all of the special characters have been removed. The white space included.

Remove everything except letters, numbers and white spaces.

If you want to keep white spaces, then you can use the following regex:

The preg_replace example above transforms our string into the following:

This is because we instructed the preg_replace function to remove all non-alphanumeric character except spaces.

Regex to remove non-alphanumeric characters – except hyphens.

What if have a username field and you want to strip out everything except letters, numbers and hyphens?

The PHP snippet takes “my-username()*&>>>>” and converts it into the following string:

clean username php

In the screenshot above, you can see that the hyphen character has been left untouched. This is unlike the asterisk and the ampersand characters, which have all been removed.

Allowing underscores.

In this example, we will remove all non-alphanumeric characters except the underscore character:

The preg_match example above results in the following string:

Removing everything except letters, numbers and full stops / dots.

If you want allow full stops, you can use the following preg_match example:

If you run the snippet above you will see that preg_match strips the forward slash, the hashtag and the underscore while ignoring the dot character.

To allow spaces AND dots, you can use the following regex:

This strips out all of the “bad” characters and leaves us with the following:

And that’s it. Hopefully, you found at least one of these examples useful!

Related: Extract numbers from a string using PHP.

Facebook Comments