douyueju2912 2017-05-20 17:22
浏览 20
已采纳

找到错误地在单引号内使用的php变量

I want to run a regex search from inside PhpStorm (could be any file manager though, Double/Total Commander handles regex searches just as well) to match php variables that are inside single quotes and therefore string interpolation won't work on them e.g. '$var'.

The content of the files would be something like this:

$var = 'Hello world!';

echo 'Lorem ipsum $var dolor sit amet'; // Match this.
echo "Lorem ipsum 'dolor sit amet $var consectetur' adipiscing elit"; // But not this.
echo "Lorem ipsum 'dolor sit amet \$var consectetur' adipiscing elit"; // Or this.

I want the regex search to match the first statement, but not the second or third.

I've tried '[\w ]+\$[\w]+[\w ]+' but that doesn't work because it matches all statements regardless of the double quotes or escaped dollar sign. (regex101).

This is just a regular regex search that I want to run on my repo to find buggy code.

What regex could I use for this?

(I don't need to get any text in between quotes, just php variables in between single quotes that aren't escaped.)

  • 写回答

1条回答 默认 最新

  • dpjtn48868 2017-05-20 20:09
    关注

    What you need is negative lookaround. In particular, negative lookahead, because in PHP you are not allowed to use no-fixed-length lookbehind:

    '[\w ]+\$[\w]+[\w ]+'(?![\w$ ']*")
    

    (?![\w$ ']*") means that the string that you want to match must not be followed by a ", with any number of character (the ones that you want to allow in a string) in the middle.

    See also: http://www.regular-expressions.info/lookaround.html

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度