duanchuang1935 2015-03-10 04:53
浏览 107
已采纳

Php Preg_Match获取数组中的引号字符串

need to get the quoted string and unquoted string in a array

Sample Data

$string='tennissrchkey1 tennissrchkey2 "tennis srch key 3" "tennis srch key 4" "tennis srch key 5"';    

Desired Output

Array
(
    [0] => tennissrchkey1
    [1] => tennissrchkey2
    [2] => tennis srch key 3
    [3] => tennis srch key 4
    [4] => tennis srch key 5
)

So far trying with this but no luck yet

if (preg_match('/"([^"]+)"/', $string, $m)) {
    echo '<pre>';
    print_r($m);   
} else {
   //preg_match returns the number of matches found, 
   //so if here didn't match pattern
}

Any Help is greatly appreciated!!!

Thanks!!!

  • 写回答

2条回答 默认 最新

  • dongzhang0243 2015-03-10 05:16
    关注

    Use preg_match_all function to do a global match. (?|....) called branch reset group. Alternatives inside a branch reset group share the same capturing groups.

    $re = '~(?|"([^"]*)"|(\S+))~m';
    $str = 'tennissrchkey1 tennissrchkey2 "tennis srch key 3" "tennis srch key 4" "tennis srch key 5"';
    preg_match_all($re, $str, $matches);
    print_r($matches[1]);
    

    DEMO

    Output:

    Array
    (
        [0] => tennissrchkey1
        [1] => tennissrchkey2
        [2] => tennis srch key 3
        [3] => tennis srch key 4
        [4] => tennis srch key 5
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀