用于数字,逗号,下划线,斜杠,连字符和空格的PHP正则表达式
问题描述:
I need a string which consists of some numbers, comma, undersocre, slash, hyphen and space.
I am almost ok. Here is my code so far.
$regex = '#^[0-9-_,/\s]+$#';
if(preg_match($regex, $string)){
return true;
} else {
return false;
}
But I want to contain at least 4 digit within 0 to 9.
for example, These are the values I want to valid:
09-12345678
123, 456, 789
12/ 34/ 56
These are the values I don't want to valid:
1,2
3/5/6
7-8-9
So, I tried like this.
$regex = '#^[0-9-_,/\s]{4,100}$#';
And,
$regex = '#^[0-9{4,100}-_,/\s]+$#';
But they are not true too. How can I do?
我需要一个由一些数字,逗号,下划线,斜线,连字符和空格组成的字符串。 p>
我几乎可以。 到目前为止,这是我的代码。 p>
$ regex ='#^ [0-9 -_,/ \ s] + $#';
if(preg_match($ regex) ,$ string)){
return true;
} else {
return false;
}
code> pre>
但我想包含至少4位数 在0到9之内。 p>
例如,
这些是我想要有效的值: p>
09-12345678
123,456 ,789
12 / 34/56
code> pre>
这些是我不想要有效的值: p>
1,2
3 / 5/6
7-8-9
code> pre>
所以,我试过这样的。 p>
$ regex ='#^ [0-9 -_,/ \ s] {4,100} $#';
code> pre>
并且, p >
$ regex ='#^ [0-9 {4,100} -_,/ \ s] + $#';
code> pre>
但它们也不是真的。
我该怎么办? p>
div>
答
You can use a lookahead based regex:
~^(?=(?:\D*\d){4})[-0-9_,/\s]+$~
-
(?=(?:\D*\d){4})
is lookahead to assert presence of at least 4 digits in input. - Also important is to keep hyphen at start or end in character class
[...]