Chinmay235
Chinmay235

Reputation: 3414

Validate a specific shortcode placeholder string

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

Upvotes: 1

Views: 1177

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

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.

Upvotes: 4

EL OUFIR Hatim
EL OUFIR Hatim

Reputation: 419

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

Upvotes: 2

Related Questions