Search code examples
phpregexpreg-matchpreg-match-all

How to know string regardless of proper format


I have variable like this

$string = "Hello World";

I want to compare its with properly format:

$formatstring = 'anystringornumber/anystringornumber/anystringornumber/anystringornumber/number';

This is my PHP usage:

$key = "Kode Parkir 1/01012015/Shift1/Suhendra/25000";
$regex = '^[A-Za-z]/[A-Za-z]/[A-Za-z]/[A-Za-z]/[0-9]^';
if (preg_match($regex, $key)) {
    echo 'Passed';
} else {
    echo 'Wrong key';
}

The result always Wrong Key.


Solution

  • You want to match alphanumeric character (letter and number), but didn't add the numbers in the regex. Also you missed + to match multiple characters. Secondly don't use ^ for enclosing the pattern. It is used as a special character in regex, which means start of string. You can use # instead. Like this:

    $regex = '#[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[0-9]+#';
    

    But if you want to use ^ and $ with their special meaning it will be like this :

    $regex = '#^[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+/[0-9]+$#';