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条)

报告相同问题?