Printing Unwanted Characters with PHP “preg_match”?



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

 Live Demo

<!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= -/_+
Updated on: 2020-10-13T07:38:47+05:30

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements