简体   繁体   English

正则表达式在PHP中不起作用

[英]Regular Expression not working in PHP

How to check below line in regular expression? 如何检查正则表达式下面的行?

[albums album_id='41'] [相册album_id = '41']

All are static except my album_id . 除了我的album_id其他所有内容都是静态的。 This may be 41 or else. 这可能是41或其他。

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] . 您需要转义第一个[并将+量词添加到[0-9] The first [ being unescaped created a character class - [albums album_id=\\'[0-9] and that is something you did not expect. 第一个[未转义]创建了一个字符类- [albums album_id=\\'[0-9] ,这是您所没有想到的。

Use 采用

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

Pattern details : 图案细节

  • ^ - start of string ^ -字符串开头
  • \\[ - a literal [ \\[ - 文字[
  • albums album_id=\\' - a literal string albums album_id=' albums album_id=\\' -文字字符串albums album_id='
  • [0-9]+ - one or more digits (thanks to the + quantifier, if there can be no digits here, use * quantifier) [0-9]+ - 一个或多个数字(由于+量,如果此处没有数字,请使用*量)
  • \\'] - a literal string '] \\'] -文字字符串']
  • $ - end of string. $ -字符串结尾。

See PHP demo : 参见PHP演示

$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) [0-9]后面的+表示您需要在0到9之间有一个或多个数字(如果要零个或多个,则可以加*代替)

To test your regex before using it in your code you can work with this website regex101 要在代码中使用正则表达式之前对其进行测试,可以使用此网站regex101

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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