How to Remove Special Characters from String in PHP

How to Remove Special Characters from String in PHP

The special characters from string can be easily removed using preg_replace() function in PHP. The preg_replace() function performs a search with the regular expression and replaces the matches with specified replacement. In the following code snippet, we will show you how to remove special characters from string using PHP.

The following example code uses preg_replace() with the Regular Expressions to remove special characters from the string in PHP.

// Remove  all the special characters except space
$cleanStr = preg_replace('/[^A-Za-z0-9 ]/', '', $string);
// Remove all the special characters except space
$string = "Re%20move,Special *Cha(racters from ^&String in PHP.";

// Remove special characters
$escapSplChar= preg_replace('/[^A-Za-z0-9]/', '', $string);

//Output
How to Remove Special Characters from String in PHP

Clean String for SEO Friendly URL

The following code cleans a string that can be used in the URI segment in PHP for generating SEO friendly URL.

function escapSplChar($string){
    // Replaces all spaces with hyphens.
    $string = str_replace(' ', '-', $string);

    // Removes special chars.
    $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
    // Replaces multiple hyphens with single one.
    $string = preg_replace('/-+/', '-', $string);
    
    return strtolower($string);
}

$output = escapSplChar($string);

//Output
how-to-remove-special-characters-from-string-in-php

Leave a Reply

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