1

I am trying to make this pattern work correctly and I just can't make it work it out. Basically, i want to validate a string that can only accept letter, numbers and the following characters: @!?_;:-,.

Here is the source code I have so far:

<?php
  $test_string = '1234bcd@!?_;:-,.';
  echo preg_match( "/^[a-z0-9@!?_;:,.]{4,12}$/i", $test_string );
?>
1
  • 2
    And the question is? By the way, the result of these two lines will be 0, as your $test_string is too long: the pattern will match only if the tested string's length is between 4 and 12. Commented Oct 3, 2012 at 13:57

3 Answers 3

2

You're trying to print an integer, which won't achieve what you're trying to do. Try this:

if( preg_match( "/^[a-z0-9@!?_;:,.]{4,12}$/i", $test_string )) {
    echo 'valid string!';
} else {
    echo 'invalid!';
}

Note that your regex deems strings to be valid if they are:

  • Between 4 and 12 characters long
  • Consist of only alpabetic characters, numbers, and the other characters you've included.

Also note that your input string is supposed to be invalid, not only because it is too long, but because it contains a dash, which is not supported by your regex:

1234bcd@!?_;:-,.
             ^
             No match

To include it in your regex, place it at the end of your character class in the regex:

preg_match( "/^[a-z0-9@!?_;:,.-]{4,12}$/i", $test_string )
                              ^
Sign up to request clarification or add additional context in comments.

4 Comments

Somehow I think the question is not about replacing 0 and 1 with something more meaningful. Yet I may be wrong, of course. )
That was my interpretation of the question :) Although it is a tad vague, so who knows!
escape the - in character class
@Macino - No, you don't need to, it's at the end of the character class (for a reason).
0

some of the characters are reserved by regexp such as . ? etc. use them with backslashes

if( preg_match( "/^[a-z0-9@!\?_;:,\.\-]{4,12}$/i", $test_string )) {  
  ...
} 

2 Comments

That's not the case when they're in a character class.
for the ? and . yes but not for the - . It's just good habit to escape these everywhere (but as you mentioned, not necessary unles they are \ ^ - ]). look at php doc.
0

This pattern works :

$test_string = '1234bcd@!?_;:-,.';

if(preg_match('/^[a-z0-9@!\?_;:,\.\-]{4,12}$/i', $test_string))
{
    echo 'Valid';
}

But in this case 1234bcd@!?_;:-,., it won't because the input string length is 16 (not between 4 and 12 characters long).

By the way, always escape meta-characters. You will find the complete list here.

Comments

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.