duanheye7423 2010-02-11 15:09
浏览 57
已采纳

从正则表达式获得比括号更多的反向引用

Ok this is really difficult to explain in English, so I'll just give an example.

I am going to have strings in the following format:

key-value;key1-value;key2-...

and I need to extract the data to be an array

array('key'=>'value','key1'=>'value1', ... )

I was planning to use regexp to achieve (most of) this functionality, and wrote this regular expression:

/^(\w+)-([^-;]+)(?:;(\w+)-([^-;]+))*;?$/

to work with preg_match and this code:

for ($l = count($matches),$i = 1;$i<$l;$i+=2) {
    $parameters[$matches[$i]] = $matches[$i+1];
}

However the regexp obviously returns only 4 backreferences - first and last key-value pairs of the input string. Is there a way around this? I know I can use regex just to test the correctness of the string and use PHP's explode in loops with perfect results, but I'm really curious whether it's possible with regular expressions.

In short, I need to capture an arbitrary number of these key-value; pairs in a string by means of regular expressions.

  • 写回答

6条回答 默认 最新

  • doutuo3575 2010-02-11 22:09
    关注

    You can use a lookahead to validate the input while you extract the matches:

    /\G(?=(?:\w++-[^;-]++;?)++$)(\w++)-([^;-]++);?/
    

    (?=(?:\w++-[^;-]++;?)++$) is the validation part. If the input is invalid, matching will fail immediately, but the lookahead still gets evaluated every time the regex is applied. In order to keep it (along with the rest of the regex) in sync with the key-value pairs, I used \G to anchor each match to the spot where the previous match ended.

    This way, if the lookahead succeeds the first time, it's guaranteed to succeed every subsequent time. Obviously it's not as efficient as it could be, but that probably won't be a problem--only your testing can tell for sure.

    If the lookahead fails, preg_match_all() will return zero (false). If it succeeds, the matches will be returned in an array of arrays: one for the full key-value pairs, one for the keys, one for the values.

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

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错