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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号