简体   繁体   中英

Escaping regular expressions in PHP

I am trying to escape a PCRE in PHP for use in a script. For some reason I can't get it to function when it has been escaped, I've only managed to get it working when the REGEX is given as a form input.

The Regex I'm using is:

$pattern = '£((http|ftp|https):\/\/)?([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?£';

So far I have tried:

preg_quote(): converts the Regex to the following and throws an error: £((http\\|ftp\\|https):\\/\\/)\\?([\\w\\-_]+(\\?:(\\?:\\.[\\w\\-_]+)+))([\\w\\-\\.,@\\?\\^\\=%&:/~\\+#]*[\\w\\-\\@\\?\\^\\=%&/~\\+#])\\?£

htmlentities(): gives error: Warning: preg_match(): Unknown modifier 'a'

addslashes(): same as above

mixture of the 3: same as above

Does anyone have an idea of what I'm doing wrong?

The pound symbol was the issue here, replacing it to an exclamation mark solved the problem. Working expression:

$pattern = '!((http|ftp|https):\/\/)?([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?!';

For some reason this is working fine with no escape functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM