0

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";
}

2 Answers 2

1

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 A-Z (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: https://www.php.net/manual/en/reference.pcre.pattern.syntax.php.

Sign up to request clarification or add additional context in comments.

Comments

0
$message=$_GET['msg'];

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

1 Comment

It's OK. But revert. which need to show wrong that shows ok and which need to show ok it's show wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.