简体   繁体   中英

Regular Expression not working in PHP

How to check below line in regular expression?

[albums album_id='41']

All are static except my album_id . This may be 41 or else.

Below my code I have tried but that one not working:

$str = "[albums album_id='41']";
$regex = '/^[albums album_id=\'[0-9]\']$/';
if (preg_match($regex, $str)) {
    echo $str . " is a valid album ID.";
} else {
    echo $str . " is an invalid ablum ID. Please try again.";
}

Thank you

You need to escape the first [ and add + quantifier to [0-9] . The first [ being unescaped created a character class - [albums album_id=\\'[0-9] and that is something you did not expect.

Use

$regex = '/^\[albums album_id=\'[0-9]+\']$/';

Pattern details :

  • ^ - start of string
  • \\[ - a literal [
  • albums album_id=\\' - a literal string albums album_id='
  • [0-9]+ - one or more digits (thanks to the + quantifier, if there can be no digits here, use * quantifier)
  • \\'] - a literal string ']
  • $ - end of string.

See PHP demo :

$str = "[albums album_id='41']";
$regex = '/^\[albums album_id=\'[0-9]+\']$/';
if (preg_match($regex, $str)) {
    echo $str . " is a valid album ID.";
} else {
    echo $str . " is an invalid ablum ID. Please try again.";
}
// => [albums album_id='41'] is a valid album ID.

You have an error in your regex code, use this :

$regex = '/^[albums album_id=\'[0-9]+\']$/'

The + after [0-9] is to tell that you need to have one or more number between 0 and 9 (you can put * instead if you want zero or more)

To test your regex before using it in your code you can work with this website regex101

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM