There are many string functions in PHP, among which the string splitting function is very commonly used. The string split function can split a string according to the specified delimiter and return an array. Below we will introduce several commonly used string splitting functions.
The explode function can split the string according to the specified delimiter and return an array. The syntax is as follows:
explode(string $separator , string $string , int $limit = PHP_INT_MAX)
Parameter explanation:
Sample code:
$str = "apple,banana,pear,orange"; $arr = explode(",", $str); print_r($arr);
Output result:
Array ( [0] => apple [1] => banana [2] => pear [3] => orange )
The str_split function can convert the string according to Divides by the specified length and returns an array. The syntax is as follows:
str_split ( string $string , int $split_length = 1 )
Parameter explanation:
Sample code:
$str = "hello world"; $arr = str_split($str); print_r($arr);
Output result:
Array ( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => [6] => w [7] => o [8] => r [9] => l [10] => d )
The strtok function can convert the string according to Split with the specified delimiter and return the first split substring. The syntax is as follows:
strtok ( string $string , string $token )
Parameter explanation:
Sample code:
$str = "apple,banana,pear,orange"; $tok = strtok($str, ","); while ($tok !== false) { echo "$tok<br>"; $tok = strtok(","); }
Output result:
apple banana pear orange
Through the above example, we can see that using the string splitting function can quickly and easily split strings for processing. In actual development, we need to choose different string splitting functions according to different needs to achieve the best processing effect.
The above is the detailed content of PHP string function example: string splitting. For more information, please follow other related articles on the PHP Chinese website!