开发者

PHP - Splitting a string with two parameters

I'm trying 开发者_如何学运维to split a string received from a $_GET in PHP, but I'm stuck, as it's more than the explode() function will handle - or so I think.

If the string I receive contains quotations marks (""), I want the split (by spaces) to keep the stuff in quotation marks intact. E.g. A result like 'Foo bar "Bar 2"' would be split into 1 --> Foo ; 2 --> bar ; 3 --> Bar 2 .

I've looked through explode(), preg_split, and similar things, but I don't understand how to split a larger string by space, whilst keeping intact substrings that are in quotation marks.

Thanks.


That's the definition of a CSV file with space as the delimiter. Use the CSV parsing function str_getcsv.

$str = 'Foo bar "Bar 2"';
$arr = str_getcsv($str, ' ');
print_r($arr);

Output:

Array
(
    [0] => Foo
    [1] => bar
    [2] => Bar 2
)

For PHP < 5.3, from the PHP manual's comments:

if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
        $fiveMBs = 5 * 1024 * 1024;
        $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
        fputs($fp, $input);
        rewind($fp);

        $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

        fclose($fp);
        return $data;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜