【问题标题】:How to extract an ID number from a string?如何从字符串中提取 ID 号?
【发布时间】:2019-05-26 18:49:56
【问题描述】:

如何使用 regex 或 preg_match 检索中间值?

$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;'

如何仅使用正则表达式或preg_matchds_user_id获取值?

【问题讨论】:

  • 你必须使用正则表达式吗?使用explode() 可能更容易。 $array = explode(';', $str);php.net/manual/en/function.explode.php
  • 我应该执行什么命令来获取特定值?使用爆炸()
  • 有点糊涂 - 但将其转换为参数字符串然后解析它会给你一个值数组 - parse_str(str_replace("; ", "&", $str), $params); 然后echo $params['ds_user_id'];

标签: php regex substr csv


【解决方案1】:

使用 preg_match 匹配ds_user_id=,然后用\K忘记那些匹配的字符,然后匹配一个或多个数字。没有捕获组,没有环视,没有解析所有的键值对,没有爆炸。

代码:(Demo)

$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;';
echo preg_match('~ds_user_id=\K\d+~', $str, $out) ? $out[0] : 'no match';

输出:

219132

【讨论】:

    【解决方案2】:

    好的,没有什么能打败 mickmackusa \K 构造。
    但是,对于 \K 受损引擎来说,这是下一个最好的事情

    (\d(?<=ds_user_id=\d)\d*)(?=;)

    解释

     (                          # (1 start), Consume many ID digits
          \d                         # First digit of ID
          (?<= ds_user_id= \d )      # Look behind, assert ID key exists before digit
          \d*                        # Optional the rest of the digits
     )                          # (1 end)
     (?= ; )                    # Look ahead, assert a colon exists
    

    这是一个动词解法(没有 \K),大约快 %30。

     (                             # (1 start), Consume many ID digits
          \d                            # First digit of ID
          (?:
               (?<! ds_user_id= \d )         # Look behind, if not ID,
               \d*                           # get rest of digits
               (*SKIP)                       # Fail, then start after this
               (?!)
            |  
               \d*                           # Rest of ID digits
          )
     )                             # (1 end)
     (?= ; )                       # Look ahead, assert a colon exists
    

    一些比较基准

    Regex1:   (\d(?:(?<!ds_user_id=\d)\d*(*SKIP)(?!)|\d*))(?=;)
    Options:  < none >
    Completed iterations:   50  /  50     ( x 1000 )
    Matches found per iteration:   1
    Elapsed Time:    0.53 s,   534.47 ms,   534473 µs
    Matches per sec:   93,550
    
    
    Regex2:   (\d(?<=ds_user_id=\d)\d*)(?=;)
    Options:  < none >
    Completed iterations:   50  /  50     ( x 1000 )
    Matches found per iteration:   1
    Elapsed Time:    0.80 s,   796.97 ms,   796971 µs
    Matches per sec:   62,737
    
    
    Regex3:   ds_user_id=\K\d+(?=;)
    Options:  < none >
    Completed iterations:   50  /  50     ( x 1000 )
    Matches found per iteration:   1
    Elapsed Time:    0.21 s,   214.55 ms,   214549 µs
    Matches per sec:   233,046
    
    
    Regex4:   ds_user_id=(\d+)(?=;)
    Options:  < none >
    Completed iterations:   50  /  50     ( x 1000 )
    Matches found per iteration:   1
    Elapsed Time:    0.23 s,   231.23 ms,   231233 µs
    Matches per sec:   216,232
    

    【讨论】:

    • 我知道你比这个帖子好。是否有其他人使用您的帐户发布答案?
    • 每次遇到数字序列时,您都在双向查看。
    • (这是我所期望的 sln。)
    【解决方案3】:

    如果我们想使用explode:

    $str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;';
    
    $arr = explode(';', $str);
    
    foreach ($arr as $key => $value) {
        if (preg_match('/ds_user_id/s', $value)) {
            $ds_user_id = explode('=', $value);
            echo $ds_user_id[1];
        }
    }
    

    输出

    219132
    

    在这里,我们还可以使用两个非捕获组和一个捕获组:

    (?:ds_user_id=)(.+?)(?:;)
    

    我们有一个左边界:

    (?:ds_user_id=)
    

    还有一个右边界:

    (?:;)
    

    我们收集我们想要的数字或我们希望使用的任何其他内容:

    (.+?)
    

    如果我们想验证我们的 ID 号,我们可以使用:

    (?:ds_user_id=)([0-9]+?)(?:;)
    

    DEMO

    我们想要的值可以简单地使用var_dump($matches[0][1]);来调用。

    测试

    $re = '/(?:ds_user_id=)(.+?)(?:;)/m';
    $str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;';
    
    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    // Print the entire match result
    var_dump($matches);
    

    输出

    array(1) {
      [0]=>
      array(2) {
        [0]=>
        string(18) "ds_user_id=219132;"
        [1]=>
        string(6) "219132"
      }
    }
    

    DEMO

    【讨论】:

    • 请要求发帖者在回答之前“尝试一下”。当这个社区被滥用为免费的代码编写服务时,鼓励更多“给我 codez”的问题。此外,当需要分解正则表达式模式的返回值时,应改为细化模式。
    • 引用块格式适用于引用的文本。在 Stackexchange 网站上,引用格式通常用于错误消息和文档中的准确引用。
    • 查看我的回答,了解如何简单地编写此任务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 2018-02-12
    相关资源
    最近更新 更多