How to remove special characters from string in PHP

Characters other than alphabet [A-Za-z] and digits [0-9] are known as special characters like symbols & ^ % @.

Removing special characters from PHP string is very easy by using php library functions like

  1. preg_replace()
  2. str_replace()

Lets see them one by one

Using preg_replace() to remove special characters from string in PHP

PHP provides preg_replace() functions to remove special characters from string.

Lets see how to remove special characters from string in PHP using Examples.

Example: remove special characters from string in PHP.

Output

Here preg_replace() is used for regular expression search and replace the string.

Syntax of preg_replace is

preg_replace($pattern, $replacement, $string)

$pattern: regular expression to find in string

$replacement: $pattern will be replaced by this

$string: The string on which we will find pattern and replace it.

Example: Remove special characters from string in PHP.

Output

In above example

preg_replace('/[^A-Za-z0-9 ]/', '', $str);

Here $pattern is regular expression that specifies.

Consider A-Z and a-Z and 0-9 characters and a space (” “) in $str string.

Other then this replace any character with ”.

Example: Remove special characters except ! and . from string in PHP.

Output

In above example two special characters are part of string ! and . we dont want to remove these two special characters for that we have included these two characters in pattern.

Using str_replace to remove special characters from PHP String

Syntax of str_replace is

str_replace($search, $replace, $string);
str_replace($search, $replace, $string, $count)

$search: The character or string you want to search on $string

$replace: $search will be replaced with $replace

$string: on given string we will apply search and replace

$count: Keep record of how many replacement performed.

Example: PHP program to remove special characters from string except dot

Output

In above example we have created a character array of special characters and we want to replace with “”.

Result of str_replace() is stored in $str1.

Removing html elements from PHP string

Output

In above example there are three html elements values showing as a part of string &bsp; > <

To remove this we used preg_replace("/&#?[a-z0-9]{2,8};/i","",$str);

This regular expression is taken from StackOverFlow

Removing comma and currency symbol from PHP String

Removing comma from currency

Output

Removing comma (,) and currency symbol from PHP string currency

Output

Using preg_replace() to remove currency symbol.

Output

If you want to remove only currency symbol and dont want to remove comma (,) then you can use following regular expression with preg_replace().

preg_replace('/[^0-9,]/s', "", $str);