简体   繁体   中英

PHP: preg_match

i need to write a case which only except the a-zA-Z0-9 characters with underscore and white space(1 or more than 1) and ignore all rest of the characters.I wrote a code but its not working properly. In those case should be wrong but its show OK

1) test msg@ 
2) test@msg  
3) test!msg

also those should be OK but currently shows wrong.

1) test msg.-(Two white space)

what i should to change in my code.pls help and see my code below.

$message=$_GET['msg'];

if(preg_match('/[^A-Za-z0-9]\W/',$message))
{
   echo "Wrong";
}
else
{
 echo "OK";
}

Here's an optimized version of the one left by riad :

$message = $_GET['msg'];

if ( preg_match('/^[a-z0-9_ ]+$/i', $message) )
{
   echo 'Ok';
}
else
{
 echo 'Wrong';
}

I've removed the AZ (uppercase) from the regular expression since the i modifier is used.

I'd also like to explain what you did wrong in the example you provided.

First, by putting the ^ inside the square brackets ([]), you're essentially doing the opposite of what you were trying to do. Place a ^ inside the square brackets means "not including."

You were missing a *, + or? at the end of the square bracket, unless you only wanted to match a single character. The * character means 0 or more, + means 1 or more and? means 0 or 1.

The \W means any non-word character. That's probably not what you wanted.

Finally, to starting a regular expression with ^ means that the beginning of the string you're string to match must start with whatever is after the ^. Ending the regular expression with a $ means that the string must end with the characters preceding the $.

So by typing /^[a-z0-9_ ]+$/i you're saying match a string that starts with a-z0-9_ or a space, that contains at least of those characters (+) and ends.

PHP has a lot of documentation of the PCRE regular syntax which you can find here: http://ca2.php.net/manual/en/reference.pcre.pattern.syntax.php .

$message=$_GET['msg'];

if(preg_match('/^[a-zA-Z0-9_ ]+$/i',$message))
{
  echo "Wrong";
}
else
{
  echo "OK";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM