dongtanjian9310 2012-12-21 13:43
浏览 175
已采纳

正则表达式从函数参数中获取字符串?

Can anyone help me with regex problem. Im making a script to go through all my .php files and get all strings passed to certain function. I need to match this cases:

/* Double quotes */
function("some string"); // Match: some string
function("some \"string\""); // Match: some "string"
function("some 'string'"); // Match: some 'string'

/* Single quotes */
function('some string'); // Match: some string
function('some \'string\''); // Match: some 'string'
function('some "string"'); // Match: some "string"

Function can also accept parameters after string, so it also needs to match this cases:

/* Additional parameters */
function("some string", "param"); // Match: some string
function("some string", $param); // Match: some string

So essentially, param can be either a string (quoted or double quoted) or unquoted variable. I need to get string only from first parameter of function, regardless if second parameter exists or is quoted in any way...

Thanks in advance...

  • 写回答

4条回答 默认 最新

  • douzhi1879 2012-12-21 14:02
    关注

    Your particular example was successfully processed with...

    preg_match_all('#\\(\\s*("((\\\\.|[^"])+)"|\'((\\\\.|[^\'])+)\'),?#s', $test, $matches);
    

    Here's ideone demo.

    Explanation: we try to match opening parenthesis (thankfully, it's PHP; it'd be far more difficult in Ruby), followed by any number of whitespace characters, followed by...

    • either "(\\.|[^"])+"
    • or '(\\.|[^'])+'

    ... followed by optional comma.

    Each of this sequences covers both 'special characters' (escaped with slash) and 'normal ones' (that are not the same as delimiters).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败