Dealing with Weird Characters in PHP

0

September 8, 2021 by al

from codex


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 Special Characters from String

The following code removes the special characters from string with regular expression pattern (Regex) in PHP.

$string = "Wel%come *to( codex<world, the |world o^f pro?gramm&ing.";

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

Output:

Welcometocodexworldtheworldofprogramming

Remove Special Characters from String Except Space

The following code removes the special characters from string except space in PHP.

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

Output:

Welcome to codexworld the world of programming

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 cleanStr($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 $string;
}

$cleanStr = cleanStr($string);

Output:

Welcome-to-codexworld-the-world-of-programming


0 comments

Sorry, comments are closed.