RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

Remove Everything Except Numbers & Letters from a String

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:

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

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:

1
$text = preg_replace("/[^a-zA-Z0-9_\s-]/", "", $text);

The output is as follows:

1
h3110   w0RlD

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:

1
$text = preg_replace("/[\s]+/", " ", $text);

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

1
$text = strtolower($text);
2
$text = str_replace(" ", "-", "$text");

PHP Functions

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

1
function createSlug($text) {
2
  $text = preg_replace("/[^A-Za-z0-9\s]/", " ", $text);
3
  $text = preg_replace("/[\s]+/", " ", $text);
4
  $text = strtolower($text);
5
  $text = str_replace(" ", "-", "$text");
6
 return $text;
7
}

Example

1
$text = "h3&&`#$110 ----w*&^%0RlD";
2
createSlug($text);

Output is:

1
h3-110-w-0rld

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:

1
function createPostSlug($text) {
2
  $text = strtolower($text);
3
  $text = preg_replace("/[^a-zA-Z0-9\s-]/", "", $text);
4
  $text = preg_replace("/[\s-]+/", " ", $text);
5
  $text = str_replace(" ", "-", "$text");
6
 return $text;
7
}

Example

1
$text = "h3&&`#$110 ----w*&^%0RlD";
2
createPostSlug($text);

Output is h3110-w0rld

See also: Create Post Slugs.

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment