dongta5747 2017-10-13 12:42
浏览 50
已采纳

RegEx Capture文字

I need a way to strip all literals from PHP files. My current regexp solution works fine when there is no nested quotes in the string. Tried updating it to handle escaped quotes as well, which did work in most cases, except when there are escaped escape characters in the string.

This is what it should be able to handle, if this should be done correctly

"text"
"\"text\""
"\\"
"\"\\\""

So as I see it, it needs to handle cases where there are an even amount of escape characters and cases where there are an uneven amount. But how do you get this into regexp?

Update

I want to clean up PHP files to make them easier to search through and index different parts, something for a small project that I am playing with. Since literals can contain mostly anything, they can also contain data similar to some of the searches. So I want to remove anything in the files that is wrapped in " or '.

"/\"[^\"]*\"/"

This will work unless there is a nested quote "\"data\"".

"/\"(\\\\\"|[^\"])*\"/"

This will work unless there is "\\"

This is what I need

$var = "...";

Becomes

$var = ;

  • 写回答

1条回答 默认 最新

  • douchuoxuan3177 2017-10-13 13:12
    关注

    You could use this regular expression based substitution:

    Find: ((?<!\\)(?:\\.)*)(["'])(?:\\.|(?!\2).)*?\2
    Replace: $1

    Note that if you are going to use this regular expression in PHP (where you encode it as a string literal) you need to escape the backslashes and quote in that regular expression, so like this:

    preg_replace("~((?<!\\\\)(?:\\\\.)*)([\"'])(?:\\\\.|(?!\\2).)*?\\2~s", "$1", $input);
    

    As PHP string literals can span multiple lines, the s modifier is added so that . matches newline characters also.

    See it run on eval.in

    NB: You'll need to think about heredoc notation also...

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

报告相同问题?

悬赏问题

  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?