简体   繁体   English

PHP Regex不匹配`\\ [`

[英]PHP Regex Not matching `\[`

I'm trying to write a regex to convert \\[#twitter:1234\\] into [#twitter:1234] ie unescape the square brackets for specific tags like Twitter, video, etc. I wrote up my expression and have tested it in Regex101 and PHPLiveRegex and it looks good but it still fails to get a match in my runtime. 我正在尝试编写一个正则表达式将\\[#twitter:1234\\] [#twitter:1234] \\[#twitter:1234\\]转换为[#twitter:1234][#twitter:1234]转义特定标签(如Twitter,视频等)的方括号。我编写了表达式并对其进行了测试Regex101PHPLiveRegex ,它看起来不错,但是在我的运行时中仍然找不到匹配项。 My actual implementation code is: 我的实际实现代码是:

$content = preg_replace( "/\\\[#((?:twitter|video|instagram|cneembed):.*?)\\\]/i", "[#$1]", $content );

If anyone has any idea why the expression isn't working your guidance would be much appreciated. 如果有人对为什么该表达式不起作用有任何想法,将非常感谢您的指导。 I'm generally pretty good at this stuff but I feel like I've gone blind on this one. 我通常在这方面很擅长,但是我觉得我对这件事视而不见。 I'm pretty certain the issue is how I'm escaping my backslashes since I can easily get the expression to match [#twitter:1234\\] just not the leading slash. 我可以肯定的问题是我如何转义反斜杠,因为我可以轻松地使表达式匹配[#twitter:1234\\]而不是前导斜杠。 Thanks! 谢谢!

问题在于,反斜杠既是字符串的转义字符,也是正则表达式的转义字符,因此您需要将所有反斜杠加倍以使它们传递到正则表达式引擎。

$content = preg_replace( "/\\\\\\[#((?:twitter|video|instagram|cneembed):.*?)\\\\\\]/i", "[#$1]", $content );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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