How to remove non-alphanumeric characters in PHP stirng?

We can remove non-alphanumeric characters from a string using the preg_replace() function in PHP. The preg_replace() function is an inbuilt function that performs regular expression search and replace operations.

Syntax

preg_replace(pattern, replacement, subject, limit, count)

Parameters

pattern: The regular expression pattern to search for.

replacement: The string or array to replace matched patterns with.

subject: The string or array to search and replace in.

limit: Optional. Maximum possible replacements for each pattern.

count: Optional. Variable that will contain the number of replacements performed.

Example

Let's demonstrate how to remove non-alphanumeric characters from a string −

<?php
    $str = "tu!tor^ials$%!poi&nt";
    echo preg_replace('/[^a-zA-Z0-9]/', '', $str);
?>
tutorialspoint

How It Works

The regular expression /[^a-zA-Z0-9]/ matches any character that is NOT alphanumeric:

  • [^...] − negated character class (matches anything NOT in the brackets)
  • a-zA-Z0-9 − alphanumeric characters (letters and digits)
  • All matched non-alphanumeric characters are replaced with empty string

Multiple Examples

<?php
    // Example with different special characters
    $text1 = "Hello@World#123!";
    $text2 = "PHP*Programming&Tutorial";
    
    echo "Original: " . $text1 . "
"; echo "Cleaned: " . preg_replace('/[^a-zA-Z0-9]/', '', $text1) . "

"; echo "Original: " . $text2 . "
"; echo "Cleaned: " . preg_replace('/[^a-zA-Z0-9]/', '', $text2); ?>
Original: Hello@World#123!
Cleaned: HelloWorld123

Original: PHP*Programming&Tutorial
Cleaned: PHPProgrammingTutorial

Conclusion

The preg_replace() function with pattern /[^a-zA-Z0-9]/ effectively removes all non-alphanumeric characters from strings. This technique is useful for data sanitization and creating clean alphanumeric strings.

Updated on: 2026-03-15T08:13:05+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements