Page 1 of 1

Replacing non alphanumeric chars in a string

Posted: Mon Feb 03, 2003 2:13 pm
by megaming
How would I remove any non-alphanumeric characters that could be present in $var?

Thanks :D

Posted: Mon Feb 03, 2003 4:29 pm
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 '');

Posted: Mon Feb 03, 2003 5:42 pm
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

Posted: Mon Feb 03, 2003 10:41 pm
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:]]!

Posted: Mon Feb 03, 2003 11:23 pm
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 =] )

Posted: Tue Feb 04, 2003 12:02 am
by lazy_yogi
wow .. thats awesome
php just seems better and better the more I see of it

btw .. thanx for the info