To print unwanted characters, use preg_match_all(). Let’s say the following is our string with some special characters −
$sentence= "M-y Name/i_s John+Doe";
We want the output to display only the special characters from the above string i.e.
-/_+
Example
The PHP code is as follows
<!DOCTYPE html> <html> <body> <?php $sentence= "M-y Name/i_s John+Doe"; echo "The original value is=",$sentence,"<br>"; if(preg_match_all('/[^a-zA-Z ]/', $sentence, $output) ){ echo "The unwanted characters are as follows= " . implode('', $output[0]); } ?> </body> </html>
Output
This will produce the following output
The original value is=M-y Name/i_s John+Doe The unwanted characters are as follows= -/_+