Europeuser
Europeuser

Reputation: 952

preg_match to check if string has specific structure

How can I check with php with preg_match() if string has specific structure. For example string is:

options:blue;white;yellow;

I want to check if string starts with string followed by : followed by n-numbers of strings separated by ;

And something which is important - string may be in Cyrillic, not only latin letters

Upvotes: 2

Views: 1528

Answers (1)

Will
Will

Reputation: 24699

Assuming only the restrictions listed in your question are needed, this will validate the string:

$number = 3;
$regex = sprintf('/^[^:]+:(?:[^;]+;){%d}$/', $number);

if (preg_match($regex, $string)) {
    echo "It matches!";
} else {
    echo "It doesn't match!";
}

Here's an example of it in action, using php -a:

php > $number = 3;
php > $regex = sprintf('/^[^:]+:(?:[^;]+;){%d}$/', $number);

php > if (preg_match($regex, 'options:blue;white;yellow;')) {
php {     echo "It matches!";
php { } else {
php {     echo "It doesn't match!";
php { }
It matches!

php > if (preg_match($regex, 'options:blue;white;yellow;green;')) {
php {     echo "It matches!";
php { } else {
php {     echo "It doesn't match!";
php { }
It doesn't match!

You can visualize this regex here. Let's break it down:

/.../          Start and end of the pattern.
^              Start of the string.
[^:]+          At least one character that is not a ':'.
:              A literal ':'.
(?:[^;]+;){N}  Exactly N occurrences of:
                   [^;]+  At least one character that is not a ';'.
                   ;      A literal ';'.
$              End of the string.

Upvotes: 2

Related Questions