This article mainly introduces you to the detailed usage of the explode() function in PHP. I hope it will be helpful to friends in need!
explode() is a built-in function in PHP that is used to split a string into different strings. The explode() function splits the string based on the string delimiter, that is, it splits the string at the positions of the delimiter. This function returns an array containing the string formed by splitting the original string.
In short, the explode() function is used to break up strings into arrays.
Syntax description:
array explode(separator, OriginalString, NoOfElements)
Parameters:
explode function accepts three parameters, two of which are mandatory, One is optional.
separator (separator): This character specifies one or more critical points, i.e., whenever this character is found in a string, it represents the end of an element of the array and The beginning of another element.
OriginalString: The string to be split in the array.
NoOfElements: This is optional. It is used to specify the number of elements of the array. This parameter can be any integer (positive, negative or zero)
Positive (N): When this parameter is passed with a positive value, it means that the array will contain this number of elements. If the number of elements after the delimiter is greater than this value, then the first N-1 elements remain unchanged and the last element is the entire remaining string.
Negative (N): If a negative value is passed as argument, then the last N elements of the array will be trimmed off and the remainder of the array will be returned as a single array.
Zero: If this parameter is zero, the returned array will have only one element, which is the entire string.
If this parameter is not provided, the returned array contains the total number of elements formed after separating the string using the delimiter.
Return type:
The return type of the explode() function is a string array.
PHP explode() function code example is as follows:
<?php // 原始字符串 $OriginalString = "Hello, How can we help you?"; // 没有可选参数NoOfElements print_r(explode(" ",$OriginalString)); // 正的NoOfElements print_r(explode(" ",$OriginalString,3)); // 负的NoOfElements print_r(explode(" ",$OriginalString,-1)); ?>
Output:
Array ( [0] => Hello, [1] => How [2] => can [3] => we [4] => help [5] => you? ) Array ( [0] => Hello, [1] => How [2] => can we help you? ) Array ( [0] => Hello, [1] => How [2] => can [3] => we [4] => help )
Related recommendations: "PHP Tutorial"
The above is the detailed content of Detailed explanation of usage of PHP explode() function. For more information, please follow other related articles on the PHP Chinese website!