1

How can I check if a string has a specific pattern like this?
XXXX-XXXX-XXXX-XXXX
4 alphanumeric characters then a minus sign, 4 times like the structure above.

What I would like to do is that I would like to check if a string contains this structure including "-".

I'm lost, can anyone point me in the correct direction?

Example code:

$string = "5E34-4512-ABAX-1E3D";

if ($pattern contains this structure XXXX-XXXX-XXXX-XXXX) {
echo 'The pattern is correct.';
}

else {
echo 'The pattern is invalid.';
}
4
  • Must XXXX be the same in every part? Or is 1234-asdf-7890-asg1 also valid? Commented Nov 23, 2015 at 11:18
  • regular expressions are your best friend. Commented Nov 23, 2015 at 11:18
  • @Sumurai8 No they can be different, like the example you posted. Commented Nov 23, 2015 at 11:18
  • @Calimero could you provide me with an example? Commented Nov 23, 2015 at 11:20

3 Answers 3

1

Use regular expressions

<?php
$subject = "XXXX-XXXX-XXXX-XXXX";
$pattern = '/^[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}$/';
if(preg_match($pattern, $subject) == 1);
    echo 'The pattern is correct.';
} else {
    echo 'The pattern is invalid.';
}
?>

[a-zA-Z0-9] match a single character

{4} matches the character Exactly 4 times

\- matches a escaped hyphen

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

1 Comment

You don't need to escape hyphen at this position ;)
0

With a perl regexp :

$string = "5E34-4512-ABAX-1E3D";

if (preg_match('/\w{4}-\w{4}-\w{4}-\w{4}/',$string)) {
    echo 'The pattern is correct.';
}

2 Comments

\w is not good because it includes underscore. Moreover, there is no start-string (^) and end-string characters ($)
@fred727 that's for the OP to decide.
0

use preg_match :

$ok = preg_match('/^([0-9A-Z]{4}-){3}[0-9A-Z]{4}$/', $string)

And if you want to consider lowercase characters, use :

$ok = preg_match('/^([0-9A-Z]{4}-){3}[0-9A-Z]{4}$/i', $string)

1 Comment

Thank you for your answer! It was a tie between you and Ashish

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.