Preg_match用于匹配"max_length[:num:]"等字符串


preg_match for matching strings like "max_length[:num:]"

我有一些字符串,如max_length[:num:],其中:num:可以是任何数字,即(max_length[50]max_length[100]等)。

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];
}

试试:http://ideone.com/a9Cux

Try with:

/max_length'[([0-9]+)']/

//编辑正如Tomalak Geret'kal所指出的,这也将匹配如下字符串:

aaa_max_length[100]

如果你只想匹配像$foo = 'max_length[100]'这样的字符串,你的regexp应该是:

/^max_length'[([0-9]+)']$/