2013-03-16 80 views
-4

我如何验证对以下规则的字符串:PHP正则表达式:如何编写规则

$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开发在这里 - 正则表达式是不是我的强项..

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

回答

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

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

$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'; 
} 
+0

+1但语法错误 - '= <'应该是'<='... – ShuklaSannidhya 2013-03-16 14:42:18

+0

@Sann谢谢,修正它。 – 2013-03-16 14:43:02

4

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

int\((第一条规则

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

\)第三个规则

+0

+1,这是一个聪明的! – 2013-03-16 14:35:30

2

这个正则表达式更小:

int\((\d1?)\) 

或无捕获组(如果你不需要检索的数值)。

int\(\d1?\)