我有一些字符串,如max_length[:num:]
,其中:num:
可以是任何数字即(max_length[50]
或max_length[100]
等)。preg_match匹配字符串,如“max_length [:num:]”
PHP中这些字符串的preg_match代码是什么?
我有一些字符串,如max_length[:num:]
,其中:num:
可以是任何数字即(max_length[50]
或max_length[100]
等)。preg_match匹配字符串,如“max_length [:num:]”
PHP中这些字符串的preg_match代码是什么?
试试这个:
'/max_length\[(\d+)\]/'
\d+
匹配一个或多个数字。
如果字符串必须只包含这个,用这个来代替:
'/^max_length\[(\d+)\]$/'
您可以使用它像这样:
$string = 'max_length[123]';
if (preg_match('/max_length\[(\d+)\]/', $string, $match)) {
$number = $match[1];
}
您可能想要使用单引号。只是要确定。 –
尝试用:
/max_length\[([0-9]+)\]/
//编辑 作为托默勒格Geret'kal指出,这也将匹配字符串,如:
aaa_max_length[100]
如果你想匹配只喜欢$ foo的琴弦= 'MAX_LENGTH [100]',您的正则表达式应为:
/^max_length\[([0-9]+)\]$/
-1懒惰。 – Hnatt
@Hnatt:就问题投票,而不是问题。 –
我做到了。刚刚向Pawan解释他为什么得到-1这个问题。因此,如果我冷静下来,SO建议添加评论,以便询问的人知道他为什么被低估。 – Hnatt