Jump to content

[SOLVED] if statement help: identifying if the user has placed invalid characters


HoTDaWg

Recommended Posts

any idea why this jumps directly to the string acceptable instance?

 

<?php

$username ="ABCDEFGhjikl(*&*%$*())*^%$#!mnop102022\/.,[]]]]]]";
if (preg_match("[a-zA-Z0-9]",$username)){
echo "Unacceptable characters are in this string";
}else{
echo "string acceptable:S \r \n {$username} ";
}
?>

again, all i want to do is identify if the variable contains specific characters.

 

any idea why this jumps directly to the string acceptable instance?

 

As you have it, you are matching any string that contains at least one alphanumeric character. If you are trying to find any strings that contain only alphanumeric characters, you'll want to do something like this:

<?php
$username ="ABCDEFGhjikl(*&*%$*())*^%$#!mnop102022\/.,[]]]]]]";

// negative match
if (preg_match('|[^a-z\d]|i', $username)) {
  // not valid
}

// positive match
if (preg_match('|^[a-z\d]+\z|i', $username)) {
  // valid match
}
?>

at the risk of sounding noobish, i am curious to know why are the specific characters |[^a-z\d]|i placed within the single quotes?

 

[pre]

"|"  == my choice of delimiter (opening)

"["  == begin a character set

"^"  == declares a negative search (match anything NOT part of this set)

"a-z" == alpha characters

"\d"  == digits

"]"  == close character set

"|"  == my choice of delimiter (closing)

"i"  == declares a case insensitive search

[/pre]

 

Hope this helps

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.