Pregunta

I have some strings like max_length[:num:]where :num: can be any number ie(max_length[50] or max_length[100] etc).

What will be the preg_match code for such strings in PHP?

¿Fue útil?

Solución

Try this:

'/max_length\[(\d+)\]/'

\d+ matches one or more digits.

If your string must contain only this, use this one instead:

'/^max_length\[(\d+)\]$/'

You can use it like this:

$string = 'max_length[123]';
if (preg_match('/max_length\[(\d+)\]/', $string, $match)) {
    $number = $match[1];
}

Try it here: http://ideone.com/a9Cux

Otros consejos

Try with:

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

//EDIT As Tomalak Geret'kal noted, this will match also strings like:

aaa_max_length[100]

If you want to match only strings like $foo = 'max_length[100]', your regexp shall be:

/^max_length\[([0-9]+)\]$/
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top