Skip to content

All topics  /  PHP

How to Remove Special Character From String in PHP

PHP ·

Hi Guys,

In this example,I will leran you how to remove special character from string in php.

you will simply and easy to use preg_replace() and str_replace() in php.

Sometimes we need to get result of an input string as a simple composition of alphabets and numbers and we want to remove all special characters by using preg_replace.

you will check to remove special character from string in php.bellow example

Example 1 : Using preg_replace


<?php
function RemoveSpecialCharacters($string){
    $result  = preg_replace('/[^a-zA-Z0-9_ -]/s','', $string);
    return $result;
}
echo RemoveSpecialCharacters("This - text ! has \\ /allot # of % special % characters");
?>

output :

This - text has allot of special characters

Example 2 : Using str_replace

<?php
function RemoveSpecialCharacters($string){
    $result = str_replace( array( '\'', '"', ',' , ';', '<', '>', '!' ), ' ', $string);

     
    return $result;
}
echo RemoveSpecialCharacters("This - text ! has \\ /allot # of % special % characters");
?>

output :

This - text has allot of special characters

It will help you.....