How to Remove Special Character From String in PHP

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this example,I will show you how to remove any special character from any string in php.

We can do this simply and easy by use preg_replace() and also str_replace() in php.

In our project sometimes we need to get result of an input string as a simple composition of alphabets and numbers and then we need to remove the all special characters by using preg_replace.

So we will check to remove special character from string by using php. Here we see in 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

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →