Loading [MathJax]/jax/output/HTML-CSS/jax.js
duanbinmi8970 2014-12-04 03:43
浏览 49
已采纳

在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?

  • 写回答

1条回答 默认 最新

  • duanlvxi8652 2014-12-04 04:12
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部