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

Asked
Viewd436795

271

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
  • @Troggy - during my edit I set out to change it to legible English, but then I realized it would probably just be a duplicate of many other questions

    John RaschJuly 14, 2009 14:31
  • Just a note, people are downvoting you because of the minimum amount of information and poorly worded question.

    TroggyJuly 14, 2009 14:28
  • No question is too basic, but you might consider to have a look at the string handler functions. Not because it is bad question but finding something in the docs feels good and sometimes faster.

    Csaba KétszeriJuly 14, 2009 15:34

10 个答案

567

尝试爆炸

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

输出:

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

如果该字符串来自csv文件,我将使用 fgetcsv() (或 str_getcsv() (如果您使用的是PHP V5.3)。这样您就可以正确解析引用的值。如果不是csv, explode() 应该是最佳选择。

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

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

0

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

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

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

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

0

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
 

这就是为什么我更喜欢 preg_split

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

整个样板:

 /** @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 : []));
}
 
2

如果您希望零件包含逗号怎么办?好吧,引用它们。那报价呢?好吧,加倍。换句话说:

part1,"part2,with a comma and a quote "" in it",part3

PHP提供了 https://php.net/str_getcsv 函数来将字符串解析为CSV文件中的一行,可以与上面的行一起使用,而不是explode

 print_r(str_getcsv('part1,"part2,with a comma and a quote "" in it",part3'));
Array
(
    [0] => part1
    [1] => part2,with a comma and a quote " in it
    [2] => part3
)
 
2

代码:

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

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

print_r($array);

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

在线:

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

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

但是可以通过广泛的方式进行手动编程:

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

输出:print_r($resultArr);

 Array
(
    [0] => ab
    [1] => cdefg
    [2] => xyx
    [3] => ht623
)
 
60
 $myString = "9,[email protected],8";
$myArray = explode(',', $myString);
foreach($myArray as $my_Array){
    echo $my_Array.'<br>';  
}
 

输出

 9
[email protected]
8