Remove special characters from string in PHP

In this tutorial, we will learn how to remove special characters from strings in PHP. We will see a built-in PHP function to remove the special characters and many more. Let’s get started.

Remove special characters from a string

Remove special characters such as |,@,! ,&,*,%,#,^etc. from a given string in PHP. While working on any project we all come across a situation where we want to either replace unwanted spaces with hyphens and also we want to clean strings that contain special characters.

Suppose we are given a string that not only contains alphanumeric characters but also special characters. To resolve such an issue in PHP we can make use of PHP built-in function preg_replace() method.

The preg_replace() method is used in such a way that it first searches for that regular expression and replaces it with the proper content which is provided by us.

Syntax:

preg_replace( pass pattern, replacement with, subject, limit, counts )
<!DOCTYPE html>
<html>
<body>

<?php 
$str = "[email protected] speedy!3*^&% tutorial#$"; 
    
 
$str = preg_replace('/[^A-Za-z\-]/', '', $str);
  
// Printing the result
echo $str; 
?>

</body>
</html>
OUTPUT:
codespeedytutorial

Suppose sometimes we want to replace spaces in our string with hyphens. So we can make use of the str_replace() method in PHP.

<!DOCTYPE html>
<html>
<body>

<?php 
$str = "[email protected] speedy!3*^&% tutorial#$"; 
    
$str = str_replace(' ','-',$str);
$str = preg_replace('/[^A-Za-z\-]/', '', $str);
  
// Printing the result
echo $str; 
?>

</body>
</html>
OUTPUT:
code-speedy-tutorial

Hope you liked this tutorial. Happy Learning !!!!!!!

Also Read: How to remove a specific value from an array in PHP

Leave a Reply

Your email address will not be published.