PHP | preg_split() Function
The preg_split() function is an inbuilt function in PHP which is used to convert the given string into an array. The function splits the string into smaller strings or sub-strings of length which is specified by the user. If the limit is specified then small string or sub-strings up to limit return through an array. The preg_split() function is similar to explode() function but the difference is used to the regular expression to specify the delimiter but explode is not used it.
array preg_split( $pattern, $subject, $limit, $flag )
Parameter: This function accepts four parameters as mentioned above and described below:
- $pattern: The value is string type which the pattern to search as a string otherwise its separates the elements.
- $subject: The $subject is variable which is used to store input string.
- $limit: The $limit is indicates the limit. If the limit is specified ,then small or sub-string to be returned up to limit.If limit is 0 or -1 ,it indicates “no limit” then used by flag ($strflag).
- $flags: The $flags is used for signalize and its variable type used for indicates two state True or False to control the program. Its combinations of different flags such as below:
- PREG_SPLIT_NO_EMPTY: If flag variable is set to PREG_SPLIT_NO_EMPTY, then only non-empty pieces will be returned by preg_split() function.
- PREG_SPLIT_DELIM_CAPTURE: If flag variable is set to PREG_SPLIT_DELIM_CAPTURE, the parenthesized expression in the delimiter pattern will be captured and returned as well.
- PREG_SPLIT_OFFSET_CAPTURE: If flag variable is set to PREG_SPLIT_OFFSET_CAPTURE, for each occurring match the appendant string offset will be returned and changes the return value in an array where matched string offset will be 0 and input string offset will be 1.
Return Value: This function returns an array after the split boundaries matched. When the limit of the original array or string exceeds then returns with an array element otherwise it’s False.
Below programs illustrate the preg_split() function in PHP:
Array (  => G  => e  => e  => k  => s  => a  => r  => t  => i  => c  => l  => e )
Array (  => Geeks  => for  => Geeks )
Array (  => Array (  => ne  => 11 )  => Array (  => arc  => 15 )  => Array (  => ive  => 19 )  => Array (  => 2018  => 23 ) )