7

I have a PHP application which should require a special activation key for unlocking. So I want to create scripts which will check if $user_input is properly formatted.

An activation key will be like this:
1E63-DE12-22F3-1FEB-8E1D-D31F

Numbers and letters spacing may vary.
So activation key may be also like this or different:
1EE3-1E1C-R21D-1FD7-111D-D3Q5

  1. Colons are separated with -
  2. Every colon contains 4 characters which are a mix of letters and numbers

Thanks in advance for any help :)

3
  • 1
    I would use regex for this, check this question: stackoverflow.com/questions/2428343/regex-for-product-key Commented Nov 3, 2013 at 20:00
  • 3
    Why do you need to check if the code if well formatted, since if they mismatch something, the format or the code, it won't work. However, I would suggest, if you want the user to type in this format, put 6 text boxes with 4 maxlength, then concatenate with - each when you recieve the input Commented Nov 3, 2013 at 20:05
  • This is just for format checking, after that input will go to further checking. Anyway, your suggestion/idea is very good so I may use it. Thank you. Commented Nov 3, 2013 at 20:34

2 Answers 2

17

You have to use a regular expression for that. I've tested this regex here: http://www.phpliveregex.com/

<?php

$key   = '1E63-DE12-22F3-1FEB-8E1D-D31F';
$regex = '^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$';

if (preg_match($regex, $key)) {
    echo 'Passed';
} else {
    echo 'Wrong key';
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works well after modification. Without modification it throws error "Warning: preg_match(): No ending delimiter '^' found" so I modified it to this $regex = '/^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/'; Thanks, your script does exactly what I wanted it to do.
2

This regex will match keys like the one you posted, and will also work if lowercase letters are included:

^([A-z0-9]){4}-([A-z0-9]){4}-([A-z0-9]){4}-([A-z0-9]){4}-([A-z0-9]){4}-([A-z0-9]){4}$

If you want only uppercase letters, change all the "z" in that regex for "Z"

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.