Home > Article > Backend Development > PHP split string function_PHP tutorial
In PHP tutorials, there are two commonly used functions to split strings, chunk_split, explode and a str_split function. This is the third one. See examples below.
Definition and Usage
The chunk_split() function splits a string into a series of smaller parts.
Grammar
chunk_split(string,length,end) parameter description
string required. Specifies the string to be split.
length is optional. A number defining the length of the string block.
end is optional. A string value that defines what is placed after each string block.
*/
$data="hello world! this is a world!"; //Define string
$new_string=chunk_split($data); //Split string
echo $new_string; //Output result
/*
Definition and Usage
The explode() function splits a string into an array.
Grammar
explode(separator,string,limit) parameter description
separator required. Specifies where to split the string.
string required. The string to split.
limit is optional. Specifies the maximum number of array elements returned.
*/
$str='one|two|three|four'; //Define string
$result=explode('|',$str,2); //Cut the string
print_r($result); //Output result
$result=explode('|',$str,-1); //Return a negative number as the number
print_r($result); //Output result
/*
Definition and Usage
The str_split() function splits a string into an array.
Grammar
str_split(string,length) parameter description
string required. Specifies the string to be split.
length is optional. Specifies the length of each array element. The default is 1.
*/
$str="hello world"; //Define string
$result=str_split($str); //Perform conversion operation
print_r($result); //Output the converted result
$result=str_split($str,4); //Each element has a fixed length of 4
print_r($result); //Output the converted result
?>