How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Remove Unwanted Characters from a String in PHP
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Remove Unwanted Characters from a String in PHP
Web Development

How to Remove Unwanted Characters from a String in PHP

how7o
By how7o
Last updated: May 22, 2026
5 Min Read
Remove unwanted characters from a PHP string with regex
SHARE

To remove unwanted characters from a string in PHP, use preg_replace() with a negated character class — keep what you want, drop the rest. The standard pattern for “letters and digits only” is preg_replace('/[^a-zA-Z0-9]/', '', $string). Tweak the character class for whitespace, dashes, dots, or other allowed characters.

Contents
  • Keep letters and digits only
  • Other common character classes
  • For URL slugs from post titles
  • Unicode-safe variant
  • When you know the exact characters to strip
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 on PHP 8.3. Originally published 2022-07-01, rewritten and updated 2026-05-17.

Keep letters and digits only

$string = 'Hello! World #1 — best post ever?';
echo preg_replace('/[^a-zA-Z0-9]/', '', $string);
// HelloWorld1bestpostever

The negated character class [^a-zA-Z0-9] matches anything not in those ranges. Replacing every match with the empty string leaves only ASCII letters and digits.

PHP remove unwanted chars — preg_replace negated class, slug pattern, Unicode \\p{L}\\p{N}

Other common character classes

// Letters only (drop digits too)
preg_replace('/[^a-zA-Z]/', '', $s);

// Letters, digits, and whitespace
preg_replace('/[^a-zA-Z0-9\s]/', '', $s);

// Letters, digits, and a few punctuation characters
preg_replace('/[^a-zA-Z0-9.,!? ]/', '', $s);

// Digits and the decimal point only
preg_replace('/[^0-9.]/', '', $s);

For URL slugs from post titles

function slugify(string $title): string {
    $s = strtolower($title);
    $s = preg_replace('/[^a-z0-9]+/', '-', $s);   // runs of non-alnum -> single dash
    return trim($s, '-');
}

echo slugify('Hello! World #1 — Best Post Ever?');
// hello-world-1-best-post-ever

This is the canonical “post title → URL slug” pattern: lowercase, collapse every run of non-alphanumeric characters into a single dash, and trim leading/trailing dashes. Works for any title that’s safe in ASCII.

Unicode-safe variant

// Keep any Unicode letter or digit (accented, CJK, Cyrillic, etc.)
preg_replace('/[^\p{L}\p{N}]/u', '', $string);

// Slug from non-Latin title (preserves the letters)
function slugifyUnicode(string $title): string {
    $s = mb_strtolower($title);
    $s = preg_replace('/[^\p{L}\p{N}]+/u', '-', $s);
    return trim($s, '-');
}

The /u flag enables Unicode mode. \p{L} matches any Unicode letter, \p{N} any Unicode digit. Without /u, accented and non-Latin characters are treated as “not letters” and stripped — usually not what you want.

When you know the exact characters to strip

$bad   = ['!', '*', '#', '+', '&'];
$clean = str_replace($bad, '', $string);

str_replace() with an array argument is faster than a regex when you know the exact characters/substrings to remove and there aren’t many of them.

Frequently asked questions

If I’m building a slug from a post title, is this regex the right tool?

It’s the building block, but a proper slug also lowercases, replaces spaces with dashes, and collapses repeated separators. The canonical pattern is: strtolower → preg_replace('/[^a-z0-9]+/', '-', $s) → trim($s, '-'). That single regex (replace runs of non-alphanumerics with one dash) does more in one pass than the bare “remove unwanted” version.

How do I keep non-Latin letters (accented characters, Cyrillic, CJK)?

Use the Unicode flag and Unicode letter classes: preg_replace('/[^\p{L}\p{N}]/u', '', $str). \p{L} matches any Unicode letter; \p{N} matches any digit including Eastern Arabic numerals. Without the /u modifier, \p{L} errors out and accented characters are stripped.

What’s the difference between preg_replace with a regex and str_replace with an array?

preg_replace with a regex defines a pattern of what to strip; str_replace([...], '', $s) takes a finite list of strings to remove. Use str_replace when you know the exact unwanted characters (or substrings), the regex when you want to express a class (“keep only letters and digits”).

Should I add htmlspecialchars() after this?

Different concern. The regex cleans the string’s content; htmlspecialchars() encodes characters that have meaning in HTML (<, >, &, ") so they don’t break markup. If your cleaned string still goes into HTML, run it through htmlspecialchars() before output — they’re complementary, not interchangeable.

Related guides

  • How to Remove All Non-Numeric Characters from a String in PHP
  • How to Get the First Character of a String in PHP
  • How to Convert a String to Uppercase in PHP

References

PHP preg_replace(): php.net/manual/en/function.preg-replace.php. PHP str_replace(): php.net/manual/en/function.str-replace.php. PCRE Unicode properties: php.net/manual/en/regexp.reference.unicode.php.

TAGGED:phpregexstrings

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Safely remove MySQL binary log files to free disk space How to Safely Clean Up MySQL Binary Log Files
Next Article Rename menu items on the WooCommerce My Account page How to Rename Menu Items on the WooCommerce My Account Page
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Make ApexCharts.js take full width of its parent
Web Development

How to Make ApexCharts.js Take the Full Width of Its Parent

5 Min Read
Create a folder in PHP if it does not already exist
Web Development

How to Create a Folder If It Does Not Exist in PHP

5 Min Read
How I Fixed Composer Dependency Errors
Web Development

How I Fixed Composer Dependency Errors Using the –ignore-platform-reqs Flag (Step-by-Step Guide)

7 Min Read
Laravel leftJoin to keep all records even without matches
Web Development

How to Use LEFT JOIN in Laravel to Keep All Records

4 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?