10

I use preg_match('/[a-z]+[0-9]/', strtolower($_POST['value'])) for check that the string contains both letters and numbers. How can I change so it just allow 5 ~ 15 characters?

/[a-z]+[0-9]{5,15}/ doesn't work.

UPDATE Now I tried:

if(preg_match('/^[a-z0-9]{5,15}$/', strtolower($_POST['value']))) {
    echo 'Valid!';
}

else {
    echo 'NOOOOO!!!';
}

If I type "dfgdfgdfg" in the input field it will say "Valid!". The value has to have both letters and numbers, and between 5-15 characters.

4
  • 5-15 characters? You mean numbers? Commented Oct 17, 2013 at 9:15
  • I hope this isn't for imposing a password "strength" ... Commented Oct 17, 2013 at 9:16
  • add some examples of correct strings and incorrect Commented Oct 17, 2013 at 9:16
  • 5-15 characters together, both numbers and letters. No, it's for the username. Commented Oct 17, 2013 at 9:19

3 Answers 3

16

The trick is to use a positive lookahead, well in this case you'll need two.

So (?=.*[0-9]) will check if there is at least a digit in your input. What's next? You guessed it, we'll just add (?=.*[a-z]). Now let's merge it with anubhava's answer:

(?=.*[0-9])(?=.*[a-z])^[a-z0-9]{5,15}$

What does this mean in general?

  • (?=.*[0-9]) : check if there is a digit
  • (?=.*[a-z]) : check if there is a letter
  • ^ : match begin of string
  • [a-z0-9]{5,15} : match digits & letters 5 to 15 times
  • $ : match end of string

From the PHP point of view, you should always check if a variable is set:

$input = isset($_POST['value']) ? strtolower($_POST['value']) : ''; // Check if $_POST['value'] is set, otherwise assign empty string to $input

if(preg_match('~(?=.*[0-9])(?=.*[a-z])^[a-z0-9]{5,15}$~', $input)){
    echo 'Valid!';
}else{
    echo 'NOOOOO!!!';
}

Online regex demo

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

2 Comments

why should I check if variable is set?
@peeter because you can never trust what the client sends or doesn't send.
9

Use line start and line end anchors with correct character class in your regex:

preg_match('/^[a-z0-9]{5,15}$/', strtolower($_POST['value']));

Your regex: /[a-z]+[0-9]/ will actually match 1 or more English letters and then a single digit.

1 Comment

Sorry I had to go for some work and couldn't attend your edited question though glad that you got a good answer from @HamZa
1

try this :

<?php

 $str = your string here

 preg_match('/^[a-z0-9]{5,15}$/', $str);

?>

1 Comment

Please never post "try this" answers on Stack Overflow.

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.