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 : neveropen,for,neveropen Output : Array ( [0] => neveropen [1] => for [2] => neveropen ) 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.
Syntax:
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 )
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.