简体   繁体   English

需要PHP正则表达式帮助

[英]PHP Regular Expression Help Needed

can anyone please tell me why this simple regex is failing? 谁能告诉我为什么这个简单的正则表达式失败?

$blogurl = 'http://www.sirpi.org/2011/02/23/';
if(preg_match("/[0-9]\/[0-9]\/[0-9]\/$/", $blogurl)){
  echo "Bad URL\n";
}

You are matching this: 您与此匹配:

one of characters 0-9
a literal slash ("/")
one of characters 0-9
a literal slash ("/")
one of characters 0-9
a literal slash ("/")
end of string

You may want to match years that have more than one digit, similarly with months and days. 您可能希望将具有多个数字的年份与月和日匹配。

/[0-9]\/[0-9]\/[0-9]\/$/

is looking for a 寻找一个

 [0-9] a single digit
 \/    followed by a /
 [0-9] a single digit
 \/    followed by a /
 [0-9] a single digit
 \/    followed by a /
 $     at the end of the string

Try 尝试

/[0-9]{1,4}\/[0-9]{1,2}\/[0-9]{1,2}\/$/

whic tests for the number of digits between each / 两次测试每个/之间的位数

you seem to be trying to test whether there are numbers in between / at the end of string. 您似乎正在尝试测试字符串末尾/之间是否存在数字。 For that you can use 为此,您可以使用

$blogurl = 'http://www.sirpi.org/2011/02/23/';
if(preg_match("/[0-9]+\/[0-9]+\/[0-9]+\/$/", $blogurl)){
  echo "Bad URL\n";
}

the + means one or more. +表示一个或多个。 Otherwise you are just matching against a single digit and the numbers there in the URL are not just single digits. 否则,您将只匹配一位数字,URL中的数字不仅是一位数字。

You can also use \\d for digits instead of [0-9] : 您也可以使用\\d代替数字[0-9]

$blogurl = 'http://www.sirpi.org/2011/02/23/';
if(preg_match("/\d+\/\d+\/\d+\/$/", $blogurl)){
  echo "Bad URL\n";
}

[0-9] matches a single digit. [0-9]匹配一个数字。 So this regex matches a single digit, a slash, a single digit, a slash, a single digit, a slash and and end of string. 因此,此正则表达式匹配一个数字,一个斜杠,一个数字,一个斜杠,一个数字,一个斜杠和字符串的结尾。

So it would match 4/5/6/ , but not 11/22/33/ . 因此它将匹配4/5/6/ ,但不匹配11/22/33/

If you want to match one or more digits, you should use [0-9]+ . 如果要匹配一个或多个数字,则应使用[0-9]+ You can also use [0-9]* if you wish to match zero or more digits. 如果您希望匹配零个或多个数字,也可以使用[0-9]*

because you are searching for single digits. 因为您要搜索一位数字。 Try this: 尝试这个:

"/[0-9]{4}\/[0-9]{2}\/[0-9]{2}\/$/"

also, if you want the number of sub url things to be variable; 此外,如果您希望子网址的数量可变,

"/(\/[0-9]+)+\/?$/"

that is, at least one / followed by a string of numbers, and then an optional finishing / . 也就是说,至少一个/后跟一串数字,然后是一个可选的结尾/

Looks like the urls are dates though from your example, so this probably isn't necessary. 看起来urls是日期,尽管来自您的示例,所以这可能不是必需的。

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

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