[PHP source code] explode and implode functions, explodeimplode

Source: Internet
Author: User
Tags php source code

[PHP source code] explode and implode functions, explodeimplode

The explode and implode functions are mainly used for conversion between strings and arrays. For example, after obtaining a parameter, you can split the string based on a character or combine the results of an array into a string for output. These two functions are often used in PHP, so it is necessary to understand their principles.


array explode ( string $delimiter, string $string, [ , $limit ] )

The function returns an array composed of strings. Each element is a substring of a string, which is separated by the string $ delimiter as the boundary point.

Parameter description


If $ limit is set and the value is positive, the returned array can contain up to $ limit elements, and the last element will contain the rest of $ string.

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

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


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

Running example
$str = 'hello,world,heiheihei,php';

Let's see if limit is not set.

$arr = explode(',', $str);print_r($arr);


When limit is a positive number, limit is set to 1 and a maximum of 1 elements are returned.

$arr = explode(',', $str, 1);print_r($arr);


Limit is a negative number, and limit is-1. All elements outside the last element are returned.

$arr = explode(',', $str, -1);print_r($arr);


Limit is 0 and treated as 1.

$arr = explode(',', $str, 0);print_r($arr);

Explode execution steps

1. Receive parameters. If the processing parameter is null

2. Create local variables used in Functions

3. Call different functions to separate strings Based on the limit Value

The core implementation of the explode function is the php_explode function. The execution flowchart of this function is as follows:

If (p2 = NULL) {// if no separator is found, the entire string add_next_index_stringl (return_value, p1, Z_STRLEN_P (str), 1) is returned directly );} else {do {// Add p1 to the return_value array add_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); // Add the last value to return_value if (p1 <= endp) add_next_index_stringl (return_value, p1, endp-p1, 1 );}Source code explanation

Sizeof ("") = 0. Sizeof has two usage methods,Sizeof (typename)AndSizeof (expression)When the parameter is typename, that is, the type name, sizeof, the size of the object corresponding to the returned type; when the parameter is an expression, sizeof calculates the size of the object corresponding to the returned type of the expression. Here, "" is an expression. sizeof is the space allocated by the compiler to "" During computation. In this case, the length of \ 0 is counted, so it is 1, while the strlen function does not calculate \ 0.

If limit is not set, the default value of limit isLONG_MAX. In the php. h file, LONG_MAX is defined as 2147483647L.

In the implementation, if the limit is greater than 1, callPhp_explodeFunction. If the limit value is less than 0, it is called.Php_explode_negative_limitFunction; If limit is equal to 0, it is treated as 1.Add_index_stringlThe function adds str to the array return_value.

The delimiterPhp_memnstrFunction
Php_memnstr (Z_STRVAL_P (str), Z_STRVAL_P (delim), Z_STRLEN_P (delim), endp );
Php_memnstr isZend_memnstrZend_memnstr implements the macro definition. Therefore, memchr in C is called to find the character delimiter.

CallAdd_next_index_stringlThe function inserts the separated strings into the returned array.


string implode ( string $glue, array $pieces )
string implode ( array $pieces )

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

Parameter description

The implode function can receive two parameter sequences. In addition, if the first parameter is an array and the second parameter is null, the second parameter defaults ''. This function can be seen as a reverse process of explode.

Of course, use the sequence specified in the document to avoid confusion.

Running example
$arr = array('hello', 'world');


Parameters in document order

$ Str = implode ('-', $ arr); // output "hello-world"


The first parameter is an array.

$ Str = implode ($ arr); // output "helloworld" $ str = implode ($ arr, '-'); // output "hello-world"


Implode execution steps

1. Receive parameters and assign values
2. If the second parameter is null, the system checks whether the type of the first parameter is an array. If not, an error is returned. Otherwise, assign a value to glue using "" and use it as the connector.
3. If the second parameter is not null, the second parameter is converted to the string type if the first parameter is of the array type. Otherwise, if the second parameter is of the array type, the first parameter is converted to the string type.
4. Call the php_implode function to connect strings.

After the implode function sets parameters, the underlying layer calls the php_implode function for string connection. The execution flow of the php_implode function is as follows:

// Traverse every element of the array, determine its type, and 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) {case IS_STRING: smart_str_appendl (& implstr, Z_STRVAL_PP (tmp), Z_STRLEN_PP (tmp); break; case IS_LONG: {char stmp [limit + 1]; str_len = slprintf (stmp, sizeof (stmp), "% ld", Z_LVAL_PP (tmp); smart_str_appendl (& implstr, stmp, Str_len);} break; case IS_BOOL: if (Z_LVAL_PP (tmp) = 1) {smart_str_appendl (& implstr, "1", sizeof ("1 ") -1);} break; case IS_NULL: break; case IS_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; case IS_OBJECT: {int copy; zval expr; zend_make_printable_zval (* tmp, & expr, & copy); sma Rt_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); convert (& implstr, Z_STRVAL (tmp_val), Z_STRLEN (tmp_val); zval_dtor (& tmp_val); break ;} // Add the glue character if (++ I! = Numelems) {smart_str_appendl (& implstr, Z_STRVAL_P (delim), Z_STRLEN_P (delim);} substring (Z_ARRVAL_P (arr), & pos );} // Add the end character 0 smart_str_0 (& implstr) at the end );


Source code explanation

Php_implode gets the content in the array one by one, then judges the type of each element, and then calls the smart_str_appendl function to append the value to the return string after necessary data type conversion. Finally, you must add an terminator to the end of the string. This is a required operation and should be noted later in programming.

Smart_str_appendlYes FunctionSmart_str_appendl_exMacro definition, this function is calledMemcpyCopy strings.


The original article is limited in writing, so it is easy to learn. If there is anything wrong with the article, please let us know.

For the time being, there will be more optimizations and common functions in the PHP source code, which will be described later in the source code reading.

If this article is helpful to you, please click here for recommendations. Thank you ^_^


Finally, I have a more detailed description of the PHP source code on github. If you are interested, you can look around and give a star. PHP5.4 source code annotation.

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.