PHP正则表达式:如何编写规则

时间:2013-03-16 14:30:23

标签: php regex

如何根据以下规则验证字符串:

$string = 'int(11)';

Rule: first 4 characters MUST be 'int('
Rule: next must be a number between 1 and 11
Rule: next must be a ')'
Rule: Everything else will fail

经验丰富的PHP开发人员 - 正则表达式不是我的强项......

欢迎任何帮助或建议。 谢谢你们..

3 个答案:

答案 0 :(得分:4)

if (preg_match('/int\((\d{1,2})\)/', $str, $matches)
    && (int) $matches[1] <= 11 && (int) $matches[1] > 0
   ) {
    // ... do something nice
} else {
    echo 'Failed!!!'
}

或者如果你不想使用pReg库(可以更快):

$str = 'int(11)';
$i = substr($str, 4, strpos($str, ')') - 4);

if (substr($str, 0, 4) === 'int('
    && $i <= 11
    && $i > 0
   ) {
    echo 'succes';
} else {
    echo 'fail';
}

答案 1 :(得分:4)

使用此正则表达式int\((\d|1[01])\)

int\((第一条规则

(\d|1[01])第二条规则

\)第三条规则

答案 2 :(得分:2)

这个正则表达式更小:

int\((\d1?)\)

或没有捕获组(如果您不需要检索数值)。

int\(\d1?\)