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

Kev*_*vin 244 php arrays string

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

我怎样才能完成这个?

输入:

9,admin@example.com,8
Run Code Online (Sandbox Code Playgroud)

Mat*_*ves 511

试试爆炸:

$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [0] => 9
    [1] => admin@example.com
    [2] => 8
)
Run Code Online (Sandbox Code Playgroud)

  • 一种方法是使用count()(又名sizeof) - http://php.net/manual/en/function.count.php (2认同)
  • @McLosysCreative您可能也喜欢`var_dump`,它提供了更详细的信息.更有用的是`var_export($ myArray,true)`因为它将`var_dump`的输出作为字符串返回,因此您可以将其存储在某些日志中而不会破坏生成的站点... (2认同)

Jak*_*ain 53

$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
foreach($myArray as $my_Array){
    echo $my_Array.'<br>';  
}
Run Code Online (Sandbox Code Playgroud)

产量

9
admin@example.com
8
Run Code Online (Sandbox Code Playgroud)


cee*_*yoz 33

$string = '9,admin@google.com,8';
$array = explode(',', $string);
Run Code Online (Sandbox Code Playgroud)

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


sou*_*rge 30

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


chx*_*chx 8

如果您希望您的部分包含逗号怎么办?好吧,引用他们的话。那么引号呢?好吧,把它们加倍。换句话说:

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
)
Run Code Online (Sandbox Code Playgroud)


ori*_*dam 5

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
Run Code Online (Sandbox Code Playgroud)

这就是为什么我更喜欢preg_split

preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)
Run Code Online (Sandbox Code Playgroud)

整个样板:

/** @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 : []));
}
Run Code Online (Sandbox Code Playgroud)