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.";
}
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.