Remove Special Character from String in PHP

In this PHP tutorial, I will discuss how to remove special character from string in PHP using preg_replace. Sometimes – We need to get result of an input string as a simple composition of alphabets and numbers and, want to remove all special characters from string by using preg_replace.

There are two options available to remove special character from string using php.

You can also check other tutorial of string,

Option 1: Using preg_replace PHP Function

We can remove special characters from sting using preg_replace, As like name its using regular expression to remove special characters from string.

Syntax of preg_replace PHP Function:

  • $pattern : The pattern to search for. It can be either a string or an array with strings.
  • $replaceWith= The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, Each pattern will be replaced by the replacement counterpart.
  • $string = This is the string which you want to filter special characters.
  • $result = This is the output string without special characters.

Remove Special Character from String in PHP:

How to Call Method:

echo RemoveSpecialChar("does't happened ' ' test");

Result:

Option 1: Using str_replace PHP Function

You can also use another PHP function str_replace() to get the same result as above script, if we know what all we have to remove special characters.

Syntax of str_replace PHP Function:

$title = str_replace( array( '\'', '"', ',' , ';', '<', '>' ), ' ', $value);

Example to Remove Special Character from String in PHP:

How to call Method

echo RemoveSpecialChar("does't happened ' ' test");

Result:

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.