In this tutorial, you will learn how to remove special or specific characters from a string in PHP.
Two methods exist to remove the special or specific character from a string with or without a regular expression:
Str_replace
PHP Function
The str_replace() function finds characters in a string and replaces some characters with others in a string.
Here is syntax:
str_replace(find,replace,string,count)
Examples of removing special characters or specific characters from strings:
Method 1: Remove Specific Character from String
We have one string if you want to remove specific characters from a string. So use the below function:
function RemoveSpecificCharacter($string){ $title = str_replace( 'World', ' Tutsmake.com ', $string); return $title; }
The above example removes “World” to Tutsmake.com. When you pass any string in this function, this function removes find “World” in a given string and replace it to “Tutsmake.com”. And return a new string.
Method 2: Remove Special Character From String
If you want to remove special character (#,@,%,&,*, etc) from string in PHP. You can use the below function for that:
function remove_special_character($string) { $t = $string; $specChars = array( ' ' => '-', '!' => '', '"' => '', '#' => '', '$' => '', '%' => '', '&' => '', '\'' => '', '(' => '', ')' => '', '*' => '', '+' => '', ',' => '', '₹' => '', '.' => '', '/-' => '', ':' => '', ';' => '', '<' => '', '=' => '', '>' => '', '?' => '', '@' => '', '[' => '', '\\' => '', ']' => '', '^' => '', '_' => '', '`' => '', '{' => '', '|' => '', '}' => '', '~' => '', '-----' => '-', '----' => '-', '---' => '-', '/' => '', '--' => '-', '/_' => '-', ); foreach ($specChars as $k => $v) { $t = str_replace($k, $v, $t); } return $t; }
The above function will remove all the special characters from the given string in PHP. If you want to add more any special character for remove in the given string, you can do it easily.
Preg_replace
PHP Function
The PHP preg_replace() function performs a regular expression for search and replace the content.
Here is Syntax:
preg_replace( $pattern, $replacement, $subject, $limit, $count );
Here are some example of preg_replace():
Example 1: Remove Special Character From String Using Regular Expression
You can use the preg_replace function to remove the special character from the string using regular expression in PHP.
function RemoveSpecialCharacter($string){ $result = preg_replace('/[^a-zA-Z0-9_ -]/s','',$string); return $result; }
Conclusion
In this tutorial, you have learned, how you can easily remove special characters or specific characters in the string using the PHP function str_replace() and preg_replace().
Grate post. Thank You for sharing useful information it is beneficial.
keep posting.