
How to Remove Special Characters from a String in PHP (With Full Examples)
Last updated 2 weeks, 5 days ago | 27 views 75 5

How to Remove Special Characters from a String in PHP (With Full Examples)
Removing special characters from strings is a common requirement in PHP when handling user inputs, sanitizing file names, creating SEO-friendly URLs, or preparing data for database storage. This guide walks you through multiple ways to remove special characters in PHP, complete with examples, best practices, and common pitfalls to avoid.
Why Remove Special Characters?
-
Sanitize user input to prevent XSS or SQL injection.
-
Create slugs or URLs from text (e.g., blog titles).
-
Clean file names for safe storage on disk.
-
Format data for APIs, XML, or CSV output.
Methods to Remove Special Characters in PHP
✅ Method 1: Using preg_replace()
The most flexible method is using regular expressions.
$input = "Hello@#% World!123";
$output = preg_replace("/[^A-Za-z0-9 ]/", '', $input);
echo $output; // Output: Hello World123
Explanation:
-
[^A-Za-z0-9 ]
→ Matches anything not a letter, digit, or space. -
Replaces special characters with an empty string.
✅ Method 2: Using filter_var()
with FILTER_SANITIZE_STRING
This is deprecated in PHP 8.1 and removed in PHP 8.3, but worth mentioning for legacy code.
$input = "Welcome<># to PHP!";
$output = filter_var($input, FILTER_SANITIZE_STRING);
echo $output; // Output: Welcome to PHP!
⚠️ Deprecated! Avoid using this in modern PHP versions.
✅ Method 3: Using str_replace()
for Specific Characters
When you know which characters to remove:
$input = "[email protected]";
$remove = ['@', '.'];
$output = str_replace($remove, '', $input);
echo $output; // Output: userdomaincom
Good for specific cleanup tasks like sanitizing emails or removing only selected symbols.
✅ Method 4: Remove All Non-Printable Characters
Useful for cleaning text from copy/paste issues or binary data.
$input = "Hello\x00World!";
$output = preg_replace('/[\x00-\x1F\x7F]/u', '', $input);
echo $output; // Output: HelloWorld!
✅ Method 5: Allow Only Letters, Digits, Dashes (Slug Generation)
function slugify($text) {
// Lowercase, remove accents
$text = iconv('UTF-8', 'ASCII//TRANSLIT', $text);
$text = strtolower($text);
// Remove non-alphanumeric and non-dash
$text = preg_replace('/[^a-z0-9-]+/', '-', $text);
$text = trim($text, '-');
return $text;
}
echo slugify("Hello World! I'm @ PHP."); // Output: hello-world-i-m-php
Full Working Example
<?php
function clean_string($string) {
// Remove everything except letters, numbers, and space
return preg_replace("/[^A-Za-z0-9 ]/", '', $string);
}
$raw = "Product Name! @ 50% OFF ##";
$cleaned = clean_string($raw);
echo "Original: " . $raw . "\n";
echo "Cleaned: " . $cleaned . "\n";
Output:
Original: Product Name! @ 50% OFF ##
Cleaned: Product Name 50 OFF
Tips
-
✅ Use
preg_replace()
for flexibility and pattern matching. -
✅ Use
iconv()
to transliterate accented characters (é → e
). -
✅ For URLs or file names, also consider replacing spaces with hyphens or underscores.
-
✅ If working with user-generated content, combine sanitization with HTML encoding:
htmlspecialchars($cleaned_text, ENT_QUOTES, 'UTF-8');
⚠️ Common Pitfalls
-
❌ Over-removing characters: Removing useful punctuation like periods or dashes when not necessary.
-
❌ Not handling UTF-8 properly:
preg_replace
needs theu
modifier for UTF-8. -
❌ Using deprecated filters: Avoid
FILTER_SANITIZE_STRING
in modern PHP (>= 8.1). -
❌ Assuming input is clean: Always validate and sanitize even from internal sources.
Conclusion
Removing special characters in PHP is simple and powerful when using the right tools like preg_replace()
and iconv()
. Whether you're cleaning user input, preparing file names, or building SEO-friendly URLs, these techniques will help you write clean, secure, and reliable PHP code.