如何将逗号分隔的字符串拆分为 PHP 中的数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1125730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:10:08  来源:igfitidea点击:

How can I split a comma delimited string into an array in PHP?

phparraysstring

提问by Kevin

I need to split my string input into an array at the commas.

我需要将我的字符串输入拆分为逗号处的数组。

How can I go about accomplishing this?

我怎样才能做到这一点?

Input:

输入:

9,[email protected],8

回答by Matthew Groves

Try explode:

尝试爆炸

$myString = "9,[email protected],8";
$myArray = explode(',', $myString);
print_r($myArray);

Output :

输出 :

Array
(
    [0] => 9
    [1] => [email protected]
    [2] => 8
)

回答by Jakir Hossain

$myString = "9,[email protected],8";
$myArray = explode(',', $myString);
foreach($myArray as $my_Array){
    echo $my_Array.'<br>';  
}

Output

输出

9
[email protected]
8

回答by ceejayoz

$string = '9,[email protected],8';
$array = explode(',', $string);

For more complicated situations, you may need to use preg_split.

对于更复杂的情况,您可能需要使用preg_split.

回答by soulmerge

If that string comes from a csv file, I would use fgetcsv()(or str_getcsv()if you have PHP V5.3). That will allow you to parse quoted values correctly. If it is not a csv, explode()should be the best choice.

如果该字符串来自 csv 文件,我会使用fgetcsv()(或者str_getcsv()如果您有 PHP V5.3)。这将允许您正确解析引用的值。如果不是csv,explode()应该是最好的选择。

回答by antelove

Code:

代码:

$string = "9,[email protected],8";

$array  = explode(",", $string);

print_r($array);

$no = 1;
foreach ($array as $line) {
    echo $no . ". " . $line . PHP_EOL;
    $no++;
};

Online:

在线的:

body, html, iframe { 
  width: 100% ;
  height: 100% ;
  overflow: hidden ;
}
<iframe src="https://ideone.com/pGEAlb" ></iframe>

回答by Gautam Rai

In simple way you can go with explode($delimiter, $string);

以简单的方式,您可以使用explode($delimiter, $string);

But in a broad way, with Manual Programming :

但从广义上讲,使用手动编程:

        $string = "ab,cdefg,xyx,ht623";
        $resultArr = [];
        $strLength = strlen($string);
        $delimiter = ',';
        $j = 0;
        $tmp = '';
        for ($i = 0; $i < $strLength; $i++) {
            if($delimiter === $string[$i]) {
                $j++;
                $tmp = '';
                continue;
            }
            $tmp .= $string[$i];
            $resultArr[$j] = $tmp;
        }

Outpou : print_r($resultArr);

输出: print_r($resultArr);

Array
(
    [0] => ab
    [1] => cdefg
    [2] => xyx
    [3] => ht623
)

回答by Mark William

The Best choice is to use the function "explode()".

最好的选择是使用函数“explode()”。

$content = "dad,fger,fgferf,fewf";
$delimiters =",";
$explodes = explode($delimiters, $content);

foreach($exploade as $explode) {
    echo "This is a exploded String: ". $explode;
}

If you want a faster approach you can use a delimiter tool like Delimiters.coThere are many websites like this. But I prefer a simple PHP code.

如果你想要更快的方法,你可以使用像Delimiters.co这样的分隔符工具有很多这样的网站。但我更喜欢简单的 PHP 代码。

回答by oriadam

explodehas some very big problems in real life usage:

explode在实际使用中存在一些非常大的问题:

count(explode(',', null)); // 1 !! 
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8

this is why i prefer preg_split

这就是为什么我更喜欢preg_split

preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)

the entire boilerplate:

整个样板:

/** @brief wrapper for explode
 * @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
 * @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
 * @param string $delimiter default ','
 * @return array|mixed
 */
public static function explode($val, $as_is = false, $delimiter = ',')
{
    // using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
    return (is_string($val) || is_int($val)) ?
        preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
        :
        ($as_is ? $val : (is_array($val) ? $val : []));
}