How To Remove Special Characters From a String In PHP

In this tutorial, we will see different methods and functions to clean a string by removing special characters in PHP.

1. Using preg_replace() with Regular Expressions:

One of the most versatile ways to remove special characters from a string is by using the preg_replace() function with regular expressions.

Regular expressions allow you to define a pattern of characters to match and replace.

Here’s an example of how to remove special characters using preg_replace():

$inputString = "Hello, @World!";

// Remove special characters using a regular expression
$cleanString = preg_replace('/[^A-Za-z0-9\-]/', '', $inputString);

echo $cleanString;

Output:

HelloWorld

In this example -

  1. The regular expression /[^A-Za-z0-9\-]/ matches any character that is not an uppercase letter (A-Z), lowercase letter (a-z), digit (0-9), or hyphen (-).
  2. The preg_replace() function replaces all such characters with an empty string, effectively removing them.

2. str_replace() to Remove Specific Character:

If you want to remove specific special characters from a string, you can use the str_replace() function. This function allows you to specify the characters you want to replace and what to replace them with.

Here’s an example:

<?php
$inputString = "Hello, @World!";

// Define an array of characters to remove
$specialChars = array("@", "!");

// Remove specific special characters using str_replace()
$cleanString = str_replace($specialChars, '', $inputString);

echo $cleanString;

Output:

Hello, World

3. Remove Extra Whitespaces:

The preg_replace() function also can remove whitespace characters (such as spaces, tabs, and line breaks) from a string. Here is an example:

$inputString = "This is a string with     extra     spaces.";

// Remove whitespace using a regular expression
$cleanString = preg_replace('/\s+/', ' ', $inputString);

echo $cleanString;

Output:

This is a string with extra spaces.