xZero
xZero

Reputation: 663

PHP check if string is properly formatted

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 :)

Upvotes: 6

Views: 18292

Answers (2)

SyntaxSwearer
SyntaxSwearer

Reputation: 41

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"

Upvotes: 2

user2518044
user2518044

Reputation:

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

Upvotes: 16

Related Questions