phpregexpreg-matchshortcodeplaceholder

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

Solution

  • 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:

    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.