« Javascript onfocus-onblur, show-hide table-div || 301 Permanent Redirect PHP and HTACCESS »

Only allow alpha/numeric characters

0


Strip all symbols and other non a-z, 1-0 characters from a string using the handy-dandy ereg_replace.

<?php
$before= "First !@#$%^&amp;*() Middle _+:?&gt;&lt;|}  Last";
$after= ereg_replace("[^A-Za-z0-9] ", "", $before);
echo $after
?>
 

And the output would be:
"First Middle Last"

---
This is very basic but I see a lot of people going about this the long way around with snippets that are 10-15 lines long (when they only need to be one)...

EDIT!:

Aken pointed out a mistake I made.

I had ereg_replace("[^A-Za-z0-9]", "", $before); when it should be ereg_replace("[^A-Za-z0-9] ", "", $before); (so that spaces are also not allowed). I have corrected the code above. I'm only human :/


This entry was posted on Wednesday, May 28th, 2008 at 8:02 pm and is filed under Blog, PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Get a Trackback link

No Comments Yet

You can be the first to comment!

Leave a comment