如果字符串具有特定结构,我如何使用preg_match()
检查php。例如,字符串是:
options:blue;white;yellow;
我想检查字符串是否以字符串开头,后跟:
,后跟由;
分隔的n个字符串
一些重要的东西 - 字符串可能是西里尔语,而不仅仅是拉丁字母
答案 0 :(得分:1)
假设只需要问题中列出的限制,这将验证字符串:
$number = 3;
$regex = sprintf('/^[^:]+:(?:[^;]+;){%d}$/', $number);
if (preg_match($regex, $string)) {
echo "It matches!";
} else {
echo "It doesn't match!";
}
以下是使用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!
您可以将此正则表达式here可视化。让我们分解一下:
/.../ 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.