How to remove special character from string in php?

In this post,we will leran you how to remove special character from string in php.

1. Code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
function removeSpecialCharacters($string){
$result = preg_replace('/[^a-zA-Z0-9_ -]/s','', $string);
return $result;
}
echo removeSpecialCharacters("This - text ! has \\ /allot # of % special % characters");
?>
<?php function removeSpecialCharacters($string){ $result = preg_replace('/[^a-zA-Z0-9_ -]/s','', $string); return $result; } echo removeSpecialCharacters("This - text ! has \\ /allot # of % special % characters"); ?>
<?php
function removeSpecialCharacters($string){
    $result  = preg_replace('/[^a-zA-Z0-9_ -]/s','', $string);
    return $result;
}

echo removeSpecialCharacters("This - text ! has \\ /allot # of % special % characters");
?>

2. Example:

Input:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"This - text ! has \\ /allot # of % special % characters"
"This - text ! has \\ /allot # of % special % characters"
"This - text ! has \\ /allot # of % special % characters"

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
This - text has allot of special characters
This - text has allot of special characters
This - text has allot of special characters