May
28
2008

Only allow alpha/numeric characters

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 :/

Written by Kevin in: PHP |

No Comments »

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress | Aeros Theme | TheBuckmaker.com WordPress Themes