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
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.
