Home > Article > Backend Development > PHP implements explore() function sample code
explode() function breaks up the string into an array. Returns an array of strings
Syntax
explode(separator,string,limit)
Parameters | Description |
---|---|
separator | Required. Specifies where to split the string. |
string | Required. The string to split. |
limit |
Optional. Specifies the number of array elements to be returned. Possible values:
|
#Note: The "separator" parameter cannot be an empty string.
The sample code is as follows:
<?php /** * PHP 实现explort() 功能的详解 */ $str = ',1,2,3,4,321321,aaa,bbb'; function myExplode($seg,$str,$limit=0){ $_ret = array(0=>''); $len = strlen($str); $slen = strlen($seg); $_limit = 0; for($i=0; $i<$len; $i++){ if(substr($str,$i,$slen) == $seg ){ $_limit++; $i += $slen-1; continue; }else{ $_ret[$_limit] .= $str[$i]; } } if($limit < 0 ) $_ret = array_slice($_ret, 0 , $limit ); else{ $_ret = $limit >= count($_ret) ? $_ret : array_merge(array_slice($_ret, 0 , $limit-1 ), array(implode( $seg , array_slice($_ret,$limit-1)))); } return $_ret; } var_dump(myExplode("4",$str)); echo "<br>"; var_dump(explode("4",$str)); echo "<br>"; ?>
Supports limit to be negative. . The delimiter is string
The above is the detailed content of PHP implements explore() function sample code. For more information, please follow other related articles on the PHP Chinese website!