PHP:正则表达式忽略引号内的转义引号

在发布此内容之前,我仔细阅读了相关问题,并且无法修改任何相关答案以使用我的方法(不擅长使用正则表达式)。


基本上,这是我现有的行:


$code = preg_replace_callback( '/"(.*?)"/', array( &$this, '_getPHPString' ), $code );


$code = preg_replace_callback( "#'(.*?)'#", array( &$this, '_getPHPString' ), $code );

它们都匹配''和之间包含的字符串""。我需要正则表达式忽略它们之间包含的转义引号。因此,之间的数据''将被忽略,\'而之间的数据""将被忽略\"。


任何帮助将不胜感激。


慕码人8056858
浏览 778回答 3
3回答

烙印99

对于大多数字符串,您需要允许转义任何内容(而不仅仅是转义引号)。例如,你很可能需要允许转义字符像"\n"和"\t"当然,转义逃逸:"\\"。这是一个经常问到的问题,很早以前就已经解决(并优化)了。杰弗里·弗里德尔(Jeffrey Friedl)在他的经典著作《精通正则表达式》(第3版)中深入探讨了这个问题(例如)。这是您要查找的正则表达式:好:"([^"\\]|\\.)*"版本1:工作正常,但效率不高。更好:"([^"\\]++|\\.)*"或"((?>[^"\\]+)|\\.)*"版本2:如果您拥有所有格限定词或原子组,则效率更高(请参阅:使用原子组方法的sin的正确答案)。最好:"[^"\\]*(?:\\.[^"\\]*)*"版本3:效率更高。实现Friedl的“展开循环”技术。不需要所有格或原子组(即可以在Javascript和其他功能较少的正则表达式引擎中使用。)这是PHP语法中针对双引号和单引号子字符串的推荐正则表达式:$re_dq = '/"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"/s';$re_sq = "/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'/s";

素胚勾勒不出你

尝试这样的正则表达式:'/"(\\\\[\\\\"]|[^\\\\"])*"/'(简短)说明:"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# match a `"`(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# open group 1&nbsp; \\\\[\\\\"]&nbsp; &nbsp; &nbsp;#&nbsp; &nbsp;match either `\\` or `\"`&nbsp; |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#&nbsp; &nbsp;OR&nbsp; [^\\\\"]&nbsp; &nbsp; &nbsp; &nbsp; #&nbsp; &nbsp;match any char other than `\` and `"`)*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # close group 1, and repeat it zero or more times"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# match a `"`以下代码段:<?php$text = 'abc "string \\\\ \\" literal" def';preg_match_all('/"(\\\\[\\\\"]|[^\\\\"])*"/', $text, $matches);echo $text . "\n";print_r($matches);?>生产:abc "string \\ \" literal" defArray(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => "string \\ \" literal"&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => l&nbsp; &nbsp; &nbsp; &nbsp; ))正如您在Ideone上看到的那样。

繁华开满天机

基于一些粗略的基准测试,这似乎与展开的循环一样快,但是更容易阅读和理解。首先,它不需要任何回溯。"[^"\\]*(\\.[^"\\]*)*"
打开App,查看更多内容
随时随地看视频慕课网APP