Remove Everything Except Numbers & Letters from a String

and like us on FB

This post will show you how to strip everything from a string except alphanumeric characters to create a post-slug.

First, I’ll demonstrate it is what the code will accomplish. Consider the following string of text:

What we’re doing in this post is essentially creating a post-slug that looks something like this: h3-110-w-0rld or, using a second function, this: h3110-w0rld.

The Method

Using PHP’s preg_replace() function:

The output is as follows:

Note the three white spaces between h3110 and w0RlD? We can remove them with another regular expression search and replace. This expression will replace multiple white spaces with a single space:

The last thing we do is make the string lower case and replace the single white spaces with a hyphen.

PHP Functions

If we create a function from the above, it’ll look like this:


Output is:

You’ll note that there’s an awful lot of hyphens separating text. A more effective means of creating a slug might be to:

  • Make string lower case.
  • Strip the string of anything other than letters, numbers, multiple spaces and multiple hyphens.
  • Replace multiple white spaces and multiple hyphens with a single hyphen.

That function looks like this:


$text = "h3&&`#$110 ----w*&^%0RlD";

Output is h3110-w0rld

See also: Create Post Slugs.