Giacomo Pigani
Giacomo Pigani

Reputation: 2306

php - Using preg_match invalidate correct regular expression

I made this regular expression: \/film\/\d{4}\/+[A-Za-z0-9._%+-]+\/*$
to match: stuffstuffstuff/film/YYYY/moviename/

So for example I need to match:http://www.mymovies.it/film/2013/moliereinbicicletta/

The Regular Expression is correct, since I tested it on Regex Pal and RegExr.

I'm pretty sure the problem is about how php handles the regex or maybe of how preg-match works, but in particular I'm sure it has something to do about escaping slashes with backslashes.

This is the code you can use to have a better understanding of the problem:

if (preg_match("\/film\/\d{4}\/+[A-Za-z0-9._%+-]+\/*$", "http://www.mymovies.it/film/2013/moliereinbicicletta/")) {
    echo "It's working, Good!";
} else {
    echo "It's not working :'(";
}

It's almost 3 a.m. and I want to sleep, but I want to get this crap done as soon as possible, it's been already 4 hours of trying and trying :'(

Upvotes: 0

Views: 112

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 99001

This works:

$url = "stuffstuffstuff/film/2013/moviename/"

if (preg_match('%.*?/film/[\d]{4}/moviename/%sim', $url)) {
    echo "It's working, Good!";
} else {
    echo "It's not working :'(";
}

Upvotes: 1

jeroen
jeroen

Reputation: 91762

You are missing the delimiters:

if (preg_match("#\/film\/\d{4}\/+[A-Za-z0-9._%+-]+\/*$#", "http://www.mymovies.it/film/2013/moliereinbicicletta/")) {
                ^ here                                ^ and here

And if you don't use the / as a delimiter (pretty common), you don't need to escape it so you could rewrite it to:

if (preg_match("#/film/\d{4}/+[A-Za-z0-9._%+-]+/*$#", "http://www.mymovies.it/film/2013/moliereinbicicletta/")) {

Upvotes: 3

Related Questions