Split a comma delimited string into an array in PHP
Given a long string separated with comma delimiter. The task is to split the given string with comma delimiter and store the result in an array.
Examples:
Input : geeks,for,geeks Output : Array ( [0] => geeks [1] => for [2] => geeks ) Input : practice, code Output : Array ( [0] => practice [1] => code )
Use explode() or preg_split() function to split the string in php with given delimiter.
PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
array explode( separator, OriginalString, NoOfElements )
PHP | preg_split() Function: The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
Syntax:
array preg_split( string $pattern, string $subject [, int $limit = -1 [, int $flags = 0 ]] )
Example:
<?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); ?> |
Array
(
[0] => 123
[1] => 456
[2] => 78
[3] => 000
)
Array
(
[0] => 123
[1] => 46
[2] => 78
[3] => 000
)
Recommended Posts:
- Convert comma separated string to array using JavaScript
- How to put string in array, split by new line in PHP ?
- How to create comma separated list from an array in PHP ?
- Create a comma separated list from an array in JavaScript
- JavaScript | Split a string with multiple separators
- Split an array into chunks in JavaScript
- p5.js | split() function
- How to get character array from string in JavaScript?
- Sort array of objects by string property value in JavaScript
- JavaScript | Check if a string is a valid JSON string
- JavaScript | Difference between String.slice and String.substring
- PHP | Program to check a string is a rotation of another string
- What is the difference between array_merge and array + array in PHP?
- PHP | Different characters in the given string
- How to check if URL contain certain string using PHP?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



