Replacing non alphanumeric chars in a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
megaming
Forum Commoner
Posts: 27
Joined: Wed Dec 25, 2002 12:31 pm

Replacing non alphanumeric chars in a string

Post by megaming »

How would I remove any non-alphanumeric characters that could be present in $var?

Thanks :D
User avatar
lazy_yogi
Forum Contributor
Posts: 243
Joined: Fri Jan 24, 2003 3:27 am

Post by lazy_yogi »

$var = preg_replace('/[^0-9a-zA-Z]/', '', $var);


[0-9a-zA-Z] means any character that is alphanumeric
[^0-9a-zA-Z] means any character that is NOT alphanumeric

so it replaces all non-alphanumeric chars with nothing (ie '');
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

there is also a class [:alnum:] defined for PCRE

Code: Select all

<?php
$subject = 'abc&%$_123';
echo preg_replace('![^[]]!', '', $subject);
?>
will do virtually the same as the example above
User avatar
lazy_yogi
Forum Contributor
Posts: 243
Joined: Fri Jan 24, 2003 3:27 am

Post by lazy_yogi »

oh ok .. cool
what's woth the exclaination marks on either side ? I haven't seen that before

Code: Select all

!&#1111;^&#1111;:alnum:]]!
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

the preg_xyz functions of php are an approximation to perl's regex syntax where one can use something like

Code: Select all

if ($s =~ /^\d+(.*)/i)
&#123; print $1; &#125;
# php
# if (preg_match('/^\d+(.*)/i', $s, $matches))
#    echo $matches&#1111;1];
perl recognizes the expression between // and so do the preg_-functions, but you may choose the delimiting character (almost) freely in php. So !! is the same as //. I only use it because my expressions contain far less often an ! than / ;)
(but was astonished the first time I saw it, too =] )
User avatar
lazy_yogi
Forum Contributor
Posts: 243
Joined: Fri Jan 24, 2003 3:27 am

Post by lazy_yogi »

wow .. thats awesome
php just seems better and better the more I see of it

btw .. thanx for the info
Post Reply