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 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";
}
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 /
[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.
精彩评论