简体   繁体   中英

Php Preg_Match to get Quoted string in array

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!!!

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
)
<?php
    $sString = 'tennissrchkey1 tennissrchkey2 "tennis srch key 3" "tennis srch key 4" "tennis srch key 5"';

    $aTmp = explode( ' "', $sString );
    $iCountPieces = count( $aTmp );
    for( $i = 0; $i < $iCountPieces; ++$i )
    {
        $aFormatted[] = trim( $aTmp[ $i ], '"' );
    }
    var_dump( $aFormatted );
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM