How to Remove Special Character from String in PHP
In this tutorial, We will inform you how to remove special character from string in PHP. we want to remove all special characters from the string by using preg_replace. So, its function will remove any special character except letter and numbers.
Using preg_replace PHP Function
some data that contains special characters (e.g. single quote, double quote. special characters removed from a string using the preg_replace function.
1 2 3 4 5 6 7 8 | <?php $string="example?"; $data = preg_replace('/[^a-zA-Z0-9_ -]/s','',$string); echo $data; //output example ?> |
Using str_replace PHP Function
some data that contains special characters (e.g. single quote, double quote. special characters removed from a string using the str_replace function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php function deleteSpecialChar($str) { // replace all special characters by empty string $res = str_replace( array( '%', '@', '\'', ';', '<', '>' ), ' ', $str); return $res; } // string example $str = "A % B @ C <D>'E;"; // Call the function $res = deleteSpecialChar($str); // Display the result echo $res; //output A B C D E ?> |
Please follow and like us: