[PHP source reading]explode and implode functions, explodeimplode_php tutorial

Source: Internet
Author: User

[PHP source reading]explode and implode functions, Explodeimplode

The explode and implode functions are primarily used as string-array operations, such as taking a parameter to split a string based on a character, or using one word to match the result of an array and outputting it as a string. These two functions are often used in PHP, so it is necessary to understand their rationale.


Array explode (string $delimiter, String $string, [, $limit])

Returns an array of strings, each of which is a substring of string, separated by the $delimiter as the boundary point.


If $limit is set and is a positive number, the returned array contains a maximum of $limit elements, and the last element will contain the remainder of the $string.

If $limit is a negative number, all elements except the last-$limit element are returned.

If $limit is 0, it will be treated as 1.


If $delimiter is empty, the function returns FALSE. If delimiter is not in a string and $limit is negative, an empty array is returned.

Core source

    //returns False if Delimiter is an empty string    if(Delim_len = =0) {php_error_docref (NULL tsrmls_cc, e_warning,"Empty delimiter");    Return_false; }    //Initialize the returned arrayArray_init (Return_value); if(Str_len = =0) {          if(Limit >=0) {              //if the string is empty and limit is greater than or equal to 0, an array containing an empty string is returned, noting that sizeof ("") = = 1Add_next_index_stringl (Return_value,"",sizeof("") -1,1); }        return; }    //initializing string variables for zstr and ZdelimZval_stringl (&zstr, str, Str_len,0); Zval_stringl (&zdelim, Delim, Delim_len,0); if(Limit >1) {        //limit greater than 1,limit default is Long_maxPhp_explode (&zdelim, &zstr, Return_value, limit); } Else if(Limit <0) {        //limit is negativePhp_explode_negative_limit (&zdelim, &zstr, Return_value, limit); } Else {        //limit is 0, treated as 1, returns the entire string, and the Add_index_stringl function appends str to the array return_valueAdd_index_stringl (Return_value,0, str, Str_len,1); }

After processing the special case and initializing the variable, call the php_explode/php_explode_negative_limit function to proceed with the next step. Here is the source code for the Php_explode function


ENDP= Z_strval_p (str) +z_strlen_p (str); //P1 point to start of stringP1 =z_strval_p (str); //P2 points to the position of the first separator, the main use of the PHP_MEMNSTR function is to find the separator positionP2 =php_memnstr (z_strval_p (str), z_strval_p (Delim), Z_strlen_p (Delim), ENDP); if(P2 = =NULL) {        //p2 null means no delimiter is found and returns the entire string directlyAdd_next_index_stringl (Return_value, p1, Z_strlen_p (str),1); } Else {         Do {            //add P1 to the Return_value array and move to the next delimiter positionAdd_next_index_stringl (Return_value, p1, P2-p1,1); P1= P2 +z_strlen_p (Delim); }  while((P2 = Php_memnstr (P1, Z_strval_p (Delim), Z_strlen_p (Delim), ENDP))! = NULL &&--limit >1); //append the last value to Return_value        if(P1 <=ENDP) Add_next_index_stringl (Return_value, p1, ENDP-P1,1); }

When implemented, calls the Add_next_index_stringl to add each string to the array return_value . Add_next_index_string is the core function of this function.

int Const Char UINT int duplicate) {    *tmp;    Make_std_zval (TMP);    ZVAL_STRINGL (TMP, str, length, duplicate);     return sizeof (Zval *), NULL);}

The ADD_NEXT_INDEX_STRINGL function calls the Zend_hash_next_index_insert function to insert str into the array. And look at the source code of the Php_explode_negative_limit function


//if delimiter is not in a string, and the limit is negative, nothing is done, and returning an empty ARRAY,P2 is null to indicate that delimiter is not in string    if(P2 = =NULL) {        /*
If limit <=-1, then nothing is done, so if there is only one string, then-1 + (limit) <= 0
Returns an empty array*/ } Else { intAllocated = Explode_alloc_step, found =0; LongI, To_return; Char**positions = Emalloc (Allocated *sizeof(Char*)); //the position of the first wordpositions[found++] =P1; Do { if(Found >=allocated) {Allocated= Found + Explode_alloc_step;/*Make sure there's enough memory space*/positions= Erealloc (positions, allocated*sizeof(Char*)); } //positions Save the starting position of each wordpositions[found++] = P1 = p2 +z_strlen_p (Delim); } while((P2 = Php_memnstr (P1, Z_strval_p (Delim), Z_strlen_p (Delim), ENDP))! =NULL); //To_return is the number of return_value, in fact equal to found-|limit|To_return = limit +found; /*limit is at least-1, so no bounds checking is required: I is never less than found*/ for(i =0; i < to_return;i++) {/*This check is to check that To_return is greater than 0*/Add_next_index_stringl (Return_value, Positions[i], (positions[i+1]-Z_strlen_p (Delim))-Positions[i],1 ); } efree (positions); }

Php_explode_negative_limit is a similar operation to Php_implode, and after finding the delimited string, call the Add_next_index_string function to add the limit + found string to the Return_ The value array.


String implode (string $glue, array $pieces)

String implode (array $pieces)

Converts the value of a one-dimensional array to a string

The implode function can receive two parameter sequences.

Core code

if(Arg2 = =NULL) {        //The second parameter is empty, and the first argument must be an array        if(Z_TYPE_PP (arg1)! =Is_array) {Php_error_docref (NULL tsrmls_cc, e_warning,"Argument must is an array"); return; } make_std_zval (Delim);#define_impl_empty ""//By default, use the ConnectZval_stringl (Delim, _impl_empty,sizeof(_impl_empty)-1,0);        Separate_zval (ARG1); Arr= *arg1; } Else {        //set the value of a parameter based on the parameter type        if(Z_TYPE_PP (arg1) = =Is_array) {arr= *arg1;            CONVERT_TO_STRING_EX (ARG2); Delim= *arg2; } Else if(Z_TYPE_PP (arg2) = =Is_array) {arr= *arg2;            CONVERT_TO_STRING_EX (ARG1); Delim= *arg1; } Else{php_error_docref (NULL tsrmls_cc, e_warning,"Invalid arguments passed"); return; }    }    //Call the Php_implode function to convertPhp_implode (Delim, arr, Return_value tsrmls_cc);

In the underlying implementation, the IMPLODE function processes the parameters and calls the Php_implode function for conversion.


//iterate through each element of the array, determine its type, and then call the Smart_str_appendl function to append the value to the string     while(ZEND_HASH_GET_CURRENT_DATA_EX (Z_arrval_p (arr), (void* *) &tmp, &pos) = =SUCCESS) {        Switch((*TMP)type) {             CaseIs_string:smart_str_appendl (&implstr, Z_STRVAL_PP (TMP), Z_STRLEN_PP (TMP));  Break;  CaseIs_long: {CharStmp[max_length_of_long +1]; Str_len= slprintf (Stmp,sizeof(STMP),"%ld", Z_LVAL_PP (TMP)); Smart_str_appendl (&implstr, Stmp, Str_len); }                 Break;  CaseIs_bool:if(Z_LVAL_PP (tmp) = =1) {Smart_str_appendl (&AMP;IMPLSTR,"1",sizeof("1")-1); }                 Break;  CaseIs_null: Break;  Caseis_double: {Char*stmp; Str_len= spprintf (&stmp,0,"%.*g", (int) EG (precision), Z_DVAL_PP (TMP)); Smart_str_appendl (&implstr, Stmp, Str_len);            Efree (STMP); }                 Break;  CaseIs_object: {intcopy;                Zval expr; Zend_make_printable_zval (*tmp, &expr, &copy); Smart_str_appendl (&implstr, Z_strval (expr), Z_strlen (expr)); if(copy) {Zval_dtor (&expr); }            }                 Break; default: Tmp_val= **tmp; Zval_copy_ctor (&tmp_val); Convert_to_string (&tmp_val); Smart_str_appendl (&Implstr, Z_strval (Tmp_val), Z_strlen (Tmp_val)); Zval_dtor (&tmp_val);  Break; }        //Add glue characters        if(++i! =Numelems) {Smart_str_appendl (&Implstr, Z_strval_p (Delim), Z_strlen_p (Delim)); } zend_hash_move_forward_ex (Z_arrval_p (arr),&POS); }    //Add a character 0 at the tailSmart_str_0 (&AMP;IMPLSTR);

As you can see, the Php_implode function iterates through each element of the array, determines its type, makes the necessary type conversions, and then calls the Smart_str_appendl function to append the value to the string. Smart_str_appendl is the core function in the implode implementation code.


#define Smart_str_appendl (dest, SRC, len) \    0)#define smart_str_ APPENDL_EX (dest, SRC, nlen, what) do {            \    register size_t __nl;                                            \    *__dest = (SMART_STR *) (dest);                        \                                                                    \    smart_str_alloc4 (__dest, (Nlen), (what), __nl);                    \    memcpy (__dest->c + __dest->len, (SRC), (nlen));                    \    __dest->len = __nl;                                                  while (0)

SMART_STR_APPENDL_EX primarily calls the memcpy function for string copying.

Original article, writing Limited, Caishuxueqian, if there is not in the text, million hope to inform.

If this article is helpful to you, click on a recommendation, thank you ^_^.

More PHP source read article:

[PHP source reading]strlen function

[PHP source Reading]strpos, strstr and Stripos, stristr functions

http://www.bkjia.com/PHPjc/1127592.html www.bkjia.com true http://www.bkjia.com/PHPjc/1127592.html techarticle [php source reading]explode and implode functions, explodeimplode explode and implode functions are mainly used as string-array operations, such as to get a parameter after a certain character to split the string, ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.