unknown modifier "?" error in regular expression in php

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mayanktalwar1988
Forum Contributor
Posts: 133
Joined: Wed Jul 08, 2009 2:44 am

unknown modifier "?" error in regular expression in php

Post by mayanktalwar1988 »

Code: Select all

(https?://)?(www.)?[0-9A-Za-z]+\.com/[0-9A-Za-z]+/\?paged=[0-9]+
i am getting this error in php

Code: Select all

Warning: preg_match_all() [function.preg-match-all]: Unknown modifier '?' in C:\xampp\htdocs\expression.php on line 19
i have test it on online testers it is giving correct results but when i ran it in preg match it gave above error
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: unknown modifier "?" error in regular expression in php

Post by cpetercarter »

Have a look at this.

When you use preg_match(), the regular expression needs to be wrapped in delimiters. You can use almost any non-alphanumeric characters as delimiters, including matching pairs of brackets. Very often, a forward slash is used as a delimiter.

In your regex, php thinks that the brackets around "https?://" are delimiters, and that what follows are modifiers, and it can't interpret the immediately following ? as a modifier, hence the error message.

To fix the regex you need to do two things. First, it should have a forward slash at the beginning and the end. Second, the forward slashes in the body of the regex need to be escaped by placing a backslash in front of them, otherwise php will think that the first of them is the terminating delimiter. So:

Code: Select all

$regex = "/(https?:\/\/)?(www.)?[0-9A-Za-z]+\.com\/[0-9A-Za-z]+\/\?paged=[0-9]+/";
mayanktalwar1988
Forum Contributor
Posts: 133
Joined: Wed Jul 08, 2009 2:44 am

Re: unknown modifier "?" error in regular expression in php

Post by mayanktalwar1988 »

yup it worked. thanks
Post Reply