Printing Unwanted Characters with PHP "preg_match"?

To print unwanted characters from a string, use preg_match_all() with a regex pattern that matches non−alphanumeric characters. This function finds all matches and stores them in an array.

Syntax

preg_match_all(pattern, subject, matches)

Parameters

The function accepts the following parameters ?

  • pattern − The regular expression pattern to search for
  • subject − The input string to search in
  • matches − Array to store all matches found

Example

Let's extract special characters from a string containing unwanted symbols ?

<?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: " . implode('', $output[0]);
} else {
    echo "No unwanted characters found.";
}
?>
The original value is: M-y Name/i_s John+Doe
The unwanted characters are: -/_+

How It Works

The regex pattern /[^a-zA-Z ]/ works as follows ?

  • [^...] − Negated character class (matches anything NOT in the brackets)
  • a-zA-Z − Matches all alphabetic characters
  • Space character − Allows regular spaces
  • Result: Matches any character that is NOT a letter or space

Conclusion

Using preg_match_all() with a negated character class effectively extracts unwanted characters from strings. The implode() function then combines all matches into a single string for display.

Updated on: 2026-03-15T09:34:35+05:30

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements