Printing Unwanted Characters with PHP “preg_match”?

PHPServer Side ProgrammingProgramming

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= -/_+
raja
Published on 13-Oct-2020 11:08:04
Advertisements