我需要在逗号处将我的字符串输入分割成一个数组。

是否有一种方法将逗号分隔的字符串分解为一个平坦的索引数组?

输入:

9,admin@example.com,8

输出:

['9', 'admin@example', '8']  

试着爆炸:

$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);

输出:

Array
(
    [0] => 9
    [1] => admin@example.com
    [2] => 8
)
$string = '9,admin@google.com,8';
$array = explode(',', $string);

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

如果该字符串来自csv文件,我将使用fgetcsv()(如果使用PHP V5.3,则使用str_getcsv())。这将允许您正确地解析引用的值。如果它不是csv,那么爆炸()应该是最好的选择。

爆炸在现实生活中有一些非常大的问题:

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 : []));
}

如果你想让你的部分包含逗号呢?好吧,引用它们。然后引号呢?把它们叠起来。换句话说:

第一部分,“part2”,用逗号加引号“in it”,第三部分

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

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
)

使用explosion()或preg_split()函数使用指定的分隔符拆分php中的字符串

// Use preg_split() function 
$string = "123,456,78,000";  
$str_arr = preg_split ("/\,/", $string);  
print_r($str_arr); 
  
// use of explode 
$string = "123,46,78,000"; 
$str_arr = explode (",", $string);  
print_r($str_arr); 

如果有人想用for-each将逗号分隔的字符串转换为列表项,那么它将帮助你… 此代码是刀片模板

@php
$data = $post->tags;
$sep_tag= explode(',', $data);
@endphp

@foreach ($sep_tag as $tag)
 <li class="collection-item">{{ $tag}}</li>
 @endforeach 
//Re-usable function
function stringToArray($stringSeperatedCommas)
{
    return collect(explode(',', $stringSeperatedCommas))->map(function ($string) {
        return trim($string) != null ? trim($string) : null;
    })->filter(function ($string) {
        return trim($string) != null;
    });
}

//Usage
$array = stringToArray('abcd, , dsdsd, dsds');
print($array);

//Result
{ "abcd", "dsdsd", "dsds" }