需要获取数组中带引号的字符串和不带引号的字符串
样本数据

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

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

到目前为止一直在努力,但还没有运气
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
}

非常感谢您的帮助!!!
谢谢!!!

最佳答案

使用preg_match_all函数进行全局匹配。(?|....)称为branch reset group。分支复位组内的备选方案共享相同的捕获组。

$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
输出:
Array
(
    [0] => tennissrchkey1
    [1] => tennissrchkey2
    [2] => tennis srch key 3
    [3] => tennis srch key 4
    [4] => tennis srch key 5
)

关于php - PHP Preg_Match获取数组中的带引号的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28956405/

10-11 03:26