简体   繁体   中英

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.

You can also use \\d for digits instead of [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. 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/ .

If you want to match one or more digits, you should use [0-9]+ . You can also use [0-9]* if you wish to match zero or more digits.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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