PHP - 使用两个参数分割字符串

发布于 2024-11-29 14:25:36 字数 294 浏览 1 评论 0原文

我正在尝试拆分从 PHP 中的 $_GET 接收到的字符串,但我被卡住了,因为它超出了explode() 函数所能处理的范围 - 或者我认为是这样。

如果我收到的字符串包含引号 (""),我希望进行拆分(按空格)以使引号中的内容保持完整。例如,像 'Foo bar "Bar 2"' 这样的结果将被拆分为 1 -->福; 2 -->酒吧 ; 3 -->酒吧 2 .

我已经浏览过explode()、preg_split和类似的东西,但我不明白如何按空格分割较大的字符串,同时保持引号中的完整子字符串。

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沐歌 2024-12-06 14:25:36

这就是以空格作为分隔符的 CSV 文件的定义。使用CSV解析函数str_getcsv

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

输出:

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

对于 PHP < 5.3,来自PHP手册的注释:

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;
    }
}

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;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文