only allow specified characters...

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
lizlazloz
Forum Commoner
Posts: 64
Joined: Mon Dec 29, 2003 7:29 am

only allow specified characters...

Post by lizlazloz »

i tried

Code: Select all

<?php

$chars=[a-z0-9];
if ( preg_match($chars, $name) )
{
do stuff....
}

?>
but it didnt work...
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Try:

Code: Select all

<?php

$name  = 'ted3';
$chars = 'a-z0-9';

if (preg_match('/^['.$chars.']+$/i', $name)) {
    echo 'yes';
} else {
	echo 'no';
}

?>
if you're only testing for alphanumeric characters though, you can avoid the regex and simply use [php_man]ctype_alnum[/php_man]():

Code: Select all

<?php

$name  = 'tede4$3';
$chars = 'a-z0-9';

if (ctype_alnum($name)) {
    echo 'yes';
} else {
	echo 'no';
}

?>
Mac
Post Reply