preg_match to check if string has specific structure

天大地大妈咪最大 提交于 2020-01-05 05:37:05

问题


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


回答1:


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.


来源:https://stackoverflow.com/questions/38302490/preg-match-to-check-if-string-has-specific-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!