To split a string in PHP, you can use the explode(separator, string, limit) function. The explode() is a built-in function that splits a string into an array. The function takes three parameters: an input string to split, a delimiter, and optionally a limit on the number of array elements. The explode() function converts a string to an array, separating the given string with a delimiter. Both separator and string are required. The optional parameter "limit" specifies the number of array elements to return. In this PHP Split String example, we split a string into an array using the explode() function. Below you can see more examples of splitting strings in PHP with a detailed description of each method. Click Execute to run the PHP Split String to Array Example online and see the result.
Splitting a PHP string using the explode() function
The explode() function converts a string into an array by a separator, where the required parameters are delimiter and string.
PHP explode() Syntax
explode(separator, string, limit)
separator: the character that specifies breakpoints or points at which the string will be split. When this character occurs in a string, it symbolizes the end of one array element and the beginning of another.
string: the string to be split into an array
limit (optional): the limit specifies the number of array elements to return. The parameter can be any integer: positive, negative, or zero. If positive, the array will contain the set number of elements. If the number of elements after the delimiter split exceeds this value, the first elements remain the same, and the last element is the entire remaining string. If negative, then the last element of the array will be truncated, and the rest of the array will be returned as a single array. If zero, the returned array will contain only one element, i.e., the entire string. If this parameter is not specified, the returned array has the total number of elements after separating the string with the separator.
How to split a string into an array by using regular expressions in PHP?
To split a string into an array using a regular expression in PHP, you use the preg_split() function. In the example below, we split a string at an arbitrary number of commas and whitespace characters, including the characters: " ", \r, \t, \n, and \f.
How to convert a string to an array of chunks in PHP?
The str_split() function converts a string into an array, splitting it into elements with a given number of characters. In the example below, we split the string into elements with the given number of characters - 2.
PHP str_split() Example
$str = 'Hello world';
$arr = str_split($str, 2);
 => He
 => ll
 => o
 => wo
 => rl
 => d