The Web Developer's Blog has been discontinued. I am now maintaining a new blog that is related to my company, Blue Piccadilly. The most popular articles from this blog (by monthly page views) have already been republished on the new blog, and indeed those original pages on this blog are being redirected to their new location. I'll probably keep these pages up here for a while. At least until the domain expires.

Clean strings with regular expressions

17-Oct-2007
Filed under: PHP, Regular expressions

The following case-insensitive regular expression snippet will strip all non-alphanumeric characters from $string.

<?php
$string
= 'abc123_%$£';
$string = preg_replace("/[^a-z\d]/i", "", $string);
echo
$string; // Result: abc123
?>

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <i> <b> <cite> <code> <a>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.