PHP: How to strip unwanted characters from a string

PHP string FAQ: How can I strip unwanted characters from a PHP string? (Also asked as, How can I delete unwanted characters from a PHP string?)


Here’s a quick PHP preg_replace example that takes a given input string, and strips all the characters from the string other than letters (the lowercase letters "a-z", and the uppercase letters "A-Z"):


$res = preg_replace("/[^a-zA-Z]/", "", $string);

If you put this line of code to work in a small PHP script, like this:


$string = "Th*()is 999 is <<>> a ~!@# sample st#$%ring.";
$res = preg_replace("/[^a-zA-Z]/", "", $string);
echo $res;


and then run that script, you’ll get the following output:


As you can see, all the other characters have been stripped from the input string, leaving only letters in the resulting string.

Strip all characters but letters and numbers from a PHP string

Next, if we want to allow numbers as well as letters, we can modify our regular expression and preg_replace code to look like this:

$res = preg_replace("/[^a-zA-Z0-9]/", "", $string);

(I'll leave that output to you.)

Strip all characters but letters, numbers, and whitespace

Finally, if you want to strip all characters from your string other than letters, numbers, and whitespace, this regular expression will do the trick:

$res = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);

(Again, I leave that output as "an exercise for the reader.")

Bonus: A complete PHP string-cleaning function

Before I go, I thought it might help to share the PHP function I wrote recently that led to this blog post.

For my purposes, I needed a PHP function to do the following things:

  • Strip all the characters from a string except the alphabet characters [a-zA-Z];
  • Limit the resulting string to eight characters;
  • Make the remaining characters lowercase.

Given those character-stripping needs, here's the source code for PHP function named cleanString I created:


// created by alvin alexander,

// take a given string,
// remove all chars except [a-zA-Z],
// make the string lowercase,
// limit the number of chars to 8.
function cleanString($string)
  // allow only letters
  $res = preg_replace("/[^a-zA-Z]/", "", $string);

  // trim what's left to 8 chars
  $res = substr($res, 0, 8);

  // make lowercase
  $res = strtolower($res);

  // return
  return $res;

// test the function
echo cleanString("iajaf1237412~!@#$%^&*()-=+_][{};:/.,<>?AAMNBVCXZLKJHG'\"");


I'm still a relative PHP newbie, but I at least know that this code works, so I thought I'd share it here. Hopefully it can help someone else who needs to strip unwanted characters out of a PHP string.