Remove special character from string in PHP; Through this tutorial, i am going to show you how to remove special character from string in PHP using function and regular expression.
Php has a number of functions and methods for removing special characters from a string. But I will tell you 2 simple method in this tutorial, so that you will be able to remove special characters from any string easily.
How to Remove Special Character from String in PHP
Use the below given examples to remove special characters from string in PHP; as follows:
- Example 1 – Remove Special Character From String using str_replace
- Example 2: Remove Special Character From String Using Regular Expression
Example 1 – Remove Special Character From String using str_replace
Using str_replace function in php, you can remove special character from string in PHP.
Let’s see the following example of how to remove special character from string in php using str_replace() function; is as follows:
function remove_special_character($string) { $t = $string; $specChars = array( ' ' => '-', '!' => '', '"' => '', '#' => '', '$' => '', '%' => '', '&' => '', '\'' => '', '(' => '', ')' => '', '*' => '', '+' => '', ',' => '', '₹' => '', '.' => '', '/-' => '', ':' => '', ';' => '', '<' => '', '=' => '', '>' => '', '?' => '', '@' => '', '[' => '', '\\' => '', ']' => '', '^' => '', '_' => '', '`' => '', '{' => '', '|' => '', '}' => '', '~' => '', '-----' => '-', '----' => '-', '---' => '-', '/' => '', '--' => '-', '/_' => '-', ); foreach ($specChars as $k => $v) { $t = str_replace($k, $v, $t); } return $t; }
Example 2: Remove Special Character From String Using Regular Expression
Using preg_replace function in php, you can remove special character from string in PHP.
Let’s see the following example of how to remove special character from string in php using preg_replace() function; is as follows:
function RemoveSpecialCharacter($string){ $result = preg_replace('/[^a-zA-Z0-9_ -]/s','',$string); return $result; }