Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression: Unknown modifier '\'

I'm having the following regular expression:

(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))

but it's giving me the following error:

Unknown modifier '\'

I tried escaping the backslashes like this:

(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))

Without any luck.. I also tried replacing the backslashes with tildes, again without luck. I've searched the internet and SO for any details about the '\' as unknown modifier but again without luck. What is going wrong here?

A code sample included on request:

$regex = '(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»“”‘’]))';
return !preg_match($regex, $url);

Thanks!

like image 438
Fabian Pas Avatar asked May 19 '26 10:05

Fabian Pas


2 Answers

Just escape the single quote using a backslash like this

$regex = '(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»“”‘’]))';

EDIT :

Regarding Unknown Modifier Warning..

I assume that you may have got that on your preg functions.

A preg pattern needs a pair of characters which delimit the pattern itself.

You should add a delimiter sort of thing see here...

$body = preg_replace("/(.*)<!-- start -->(.*)<!-- end -->(.*)/","$2",$body);
                ------^                                 -----^

Source

like image 146
Shankar Narayana Damodaran Avatar answered May 22 '26 01:05

Shankar Narayana Damodaran


You have to add delimiter arround your regex:

$regex = '~(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»“”‘’]))~';

As delimiter, you can use almost any character except spaces or word character.
I recommend you to use a character that is not present in your regex, so you haven't to escape it.
Here I'm using ~

like image 35
Toto Avatar answered May 21 '26 23:05

Toto