Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to remove non-alphanumeric characters from string
To remove non-alphanumeric characters from a string in PHP, you can use the preg_replace() function with regular expressions. This function searches for a pattern and replaces it with specified content.
Method 1: Using [^a-z0-9] Pattern
The most common approach uses a negated character class to match anything that's not alphanumeric −
<?php
$my_str = "Thisis!@sample*on&ly)#$";
$my_str = preg_replace('/[^a-z0-9]/i', '', $my_str);
echo "The non-alphanumeric characters removed gives the string as ";
echo $my_str;
?>
The non-alphanumeric characters removed gives the string as Thisissampleonly
The pattern /[^a-z0-9]/i means:
-
[^a-z0-9]− Match any character that is NOT a lowercase letter or digit -
iflag − Makes the pattern case-insensitive
Method 2: Using \W Pattern
The \W pattern matches non-word characters (anything except letters, digits, and underscores) −
<?php
$my_str = "This!#is^&*a)(sample*+_only";
$my_str = preg_replace('/\W/', '', $my_str);
echo "The non-alphanumeric characters removed gives the string as ";
echo $my_str;
?>
The non-alphanumeric characters removed gives the string as Thisisasample_only
Note: The \W pattern preserves underscores since they're considered word characters, while [^a-z0-9] removes them.
Method 3: Strict Alphanumeric Only
To remove underscores as well and keep only letters and numbers −
<?php
$my_str = "Hello_World123!@#";
$my_str = preg_replace('/[^A-Za-z0-9]/', '', $my_str);
echo "Strict alphanumeric result: " . $my_str;
?>
Strict alphanumeric result: HelloWorld123
Comparison
| Pattern | Preserves Letters | Preserves Digits | Preserves Underscores |
|---|---|---|---|
/[^a-z0-9]/i |
Yes | Yes | No |
/\W/ |
Yes | Yes | Yes |
Conclusion
Use /[^a-z0-9]/i for strict alphanumeric filtering or /\W/ if you want to preserve underscores. Both methods effectively clean strings by removing unwanted special characters.
