Question

I would like to use preg_match in PHP to test the format of a URL. The URL looks like this:

/2013/09/05/item-01.html

I'm trying to get this to work :

if (preg_match("/([0-9]{4})\/([0-9]{2})\/([0-9]{2})/[.]+[.html]$", $_SERVER['REQUEST_URI'])) :
    echo "match";
endif;

But something's not quite right. Any ideas?

Était-ce utile?

La solution

Try:

if (preg_match('!\d{4}/\d{2}/\d{2}/.*\.html$!', $_SERVER['REQUEST_URI'])) {
    echo 'match';
}

\d is short for [0-9] and you can use different start/end delimiters (I use ! in this case) to make the regexp more readable when you're trying to match slashes.

Autres conseils

It looks like you are nearly correct with what you have, though you have some minor problems

  1. you forgot to escape your last "/" before the page.html
  2. the [.]+ should be [^.]+, you aren't looking for 1 or more periods, you are looking for anything not a period.
  3. You shouldnt be using the [] to match the html, but rather () or nothing at all
if (preg_match("/([0-9]{4})\/([0-9]{2})\/([0-9]{2})\/([^.]+.html)$", $_SERVER['REQUEST_URI'])) :
    echo "match";
endif;

Also you should probably learn when to use the (), these are used to make sure you are storing whatever is matched inside them. In your case I'm not sure if you want to be storing every directory up until the file or not.

My guess is you had a working expression for a file path, and it stopped working when you tried to add the file name part.

preg_match() requires a pair of delimiter characters to be specified; one at each end of the expression. It looks like you have these, but you've put an extra bit of the expression (ie the file name) at the end of the string outside of the delimiters. This is invalid.

  "/([0-9]{4})\/([0-9]{2})\/([0-9]{2})/[.]+[.html]$"
   ^                                  ^
your start delimiter             your end delimiter

You need to move the expression code [.]+[.html]$ that is currently after the end delimiter so that it is inside it.

That should solve the problem.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top