[php] How can I split a delimited string into an array in PHP?

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

This question is related to php arrays string

The answer is


The Best choice is to use the function "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.co There are many websites like this. But I prefer a simple PHP code.


What if you want your parts to contain commas? Well, quote them. And then what about the quotes? Well, double them up. In other words:

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

PHP provides the https://php.net/str_getcsv function to parse a string as if it were a line in a CSV file which can be used with the above line instead of 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
)

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

Output

9
[email protected]
8

In simple way you can go with 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);

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

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:

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


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.


Use explode() or preg_split() function to split the string in php with given delimiter

// 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); 

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

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


explode has some very big problems in real life usage:

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('@,@', $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 : []));
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript