Table of Contents
[PHP source code reading] explode and implode functions, explodeimplode
explode
Parameter description
Run the example
explode execution steps
Source code interpretation
implode执行步骤
源码解读
小结
Home Backend Development PHP Tutorial [PHP source code reading] explode and implode functions, explodeimplode_PHP tutorial

[PHP source code reading] explode and implode functions, explodeimplode_PHP tutorial

Jul 12, 2016 am 08:51 AM
explode

[PHP source code reading] explode and implode functions, explodeimplode

explode and implode functions are mainly used for conversion operations between strings and arrays, such as obtaining a parameter and then according to a certain Character splits the string, or combines the result of an array into a string output using one character. These two functions are often used in PHP, so it is necessary to understand their principles.

explode

<p>array explode ( string $delimiter, string $string, [ , $limit ] )</p>
Copy after login

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

Parameter description

limit

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

If $limit is a negative number, return all elements except the last -$limit elements.

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

delimiter

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.

Run the example

<span>$str</span> = 'hello,world,heiheihei,php';
Copy after login

Let’s first look at the situation without setting a limit

<span>$arr</span> = <span>explode</span>(',', <span>$str</span><span>);
</span><span>print_r</span>(<span>$arr</span>);
Copy after login

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

<span>$arr</span> = <span>explode</span>(',', <span>$str</span>, 1<span>);
</span><span>print_r</span>(<span>$arr</span>);
Copy after login

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

<span>$arr</span> = <span>explode</span>(',', <span>$str</span>, -1<span>);
</span><span>print_r</span>(<span>$arr</span>);
Copy after login

limit is 0 and is treated as 1.

<span>$arr</span> = <span>explode</span>(',', <span>$str</span>, 0<span>);
</span><span>print_r</span>(<span>$arr</span>);
Copy after login

explode execution steps

<p>1、接收参数,处理参数为空的情况</p>
<p>2、创建函数中使用的局部变量</p>
<p>3、根据limit的值调用不同的函数分隔字符串</p>
Copy after login

The core implementation of the explode function is the php_explode function. The following is the execution flow chart of this function:

[PHP source code reading] explode and implode functions, explodeimplode_PHP tutorial if (p2 == NULL) { // If the separator is not found, the entire string is returned directly add_next_index_stringl(return_value, p1, Z_STRLEN_P(str), 1); } 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 interpretation

sizeof("") == 0. sizeof has two uses, sizeof(typename) and sizeof(expression). When the parameter is typename, that is, the type name, sizeof returns the size of the object corresponding to the type; when the parameter is expression expression, sizeof calculates the size of the object corresponding to the return type of the expression. Here, "" is an expression. sizeof calculates the space allocated to "" by the compiler during compilation. At this time, it must be included

If limit is not set, the default value of limit is

LONG_MAX. In the php.h file, LONG_MAX is defined as 2147483647L.

In the implementation, if the limit is greater than 1, the

php_explode function is called; if the limit is less than 0, the php_explode_negative_limit function is called; if the limit is equal to 0, it is treated as 1. At this time, call the add_index_stringl function to add str to the array return_value.

When searching for the delimiter delimiter, the

php_memnstr function was called
php_memnstr(Z_STRVAL_P(str), Z_STRVAL_P(delim), Z_STRLEN_P(delim), endp); And php_memnstr is the macro definition of
zend_memnstr, which is implemented in zend_memnstr, so memchr in C is actually called to find the character delimiter.

After finding the position of the separator, call the

add_next_index_stringl function to insert the separated string into the return array.

implode

<p>string implode ( string $glue, array $pieces )<br />string implode ( array $pieces )</p>



Copy after login
Convert the value of a one-dimensional array to a string

Parameter description

The implode function can receive two parameter orders. Also, if the first parameter is an array and the second parameter is empty, the second parameter is the default value ''. This function can be seen as the reverse process of explode.

Of course, use the documented order to avoid confusion.

Run the example

<span>$arr</span> = <span>array</span>('hello', 'world');
Copy after login

Parameters in document order

<span>$str</span> = <span>implode</span>('-&lsquo;, $arr);// 输出"hello-world"
Copy after login

The first parameter is an array

<span>$str</span> = <span>implode</span>(<span>$arr</span><span>); // 输出"helloworld"
</span><span>$str</span> = <span>implode</span>(<span>$arr</span>, '-'); // 输出"hello-world"
Copy after login

implode执行步骤

<p>1、接收参数并赋值<br />2、如果第二个参数为空,则判断第一个参数的类型是否为数组,如果不是,则报错。否则,则使用""对glue赋值,使用其作为连接符。<br />3、如果第二个参数不为空,那么,如果第一个参数是数组类型,则将第二个参数转换成字符串类型;否则,如果第二个参数是数组类型,则将第一个参数转换成字符串类型。<br />4、调用php_implode函数做字符串的连接。</p>



Copy after login

在implode函数设置完参数之后,底层就调用php_implode函数进行字符串连接,php_implode函数的执行流程图如下:

[PHP source code reading] explode and implode functions, explodeimplode_PHP tutorial // 遍历数组的每一个元素,判断其类型,然后调用smart_str_appendl函数将值追加到字符串中 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[MAX_LENGTH_OF_LONG + 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); 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; } // 添加glue字符 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); } // 在尾部添加结束字符0 smart_str_0(&implstr);

 

源码解读

php_implode会逐个获取数组里面的内容,然后判断每个元素的类型,再做必要的数据类型转换之后,调用smart_str_appendl函数将值追加到返回的字符串后面。最后,还要在字符串后面加上结束符,这是个必须的操作,以后编程时也应注意。

smart_str_appendl是函数smart_str_appendl_ex的宏定义,该函数调用了memcpy做字符串的复制。

小结

原创文章,文笔有限,才疏学浅,文中若有不正之处,万望告知。

暂且写这么多吧,还有更多的优化和PHP源码中常用的函数,将会在以后的源码阅读中慢慢讲述。

如果本文对你有帮助,请点下推荐吧,谢谢^_^

 

最后,我在github有对PHP源码更详细的注解。感兴趣的可以围观一下,给个star。PHP5.4源码注解。

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1128118.htmlTechArticle[PHP source code reading] explode and implode functions, explodeimplode explode and implode functions are mainly used for conversion between strings and arrays Operations, such as obtaining a parameter and then dividing it according to a certain character...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP explode function and solve errors How to use PHP explode function and solve errors Mar 10, 2024 am 09:18 AM

The explode function in PHP is a function used to split a string into an array. It is very common and flexible. In the process of using the explode function, we often encounter some errors and problems. This article will introduce the basic usage of the explode function and provide some methods to solve the error reports. 1. Basic usage of the explode function In PHP, the basic syntax of the explode function is as follows: explode(string$separator,string$stri

Split and merge strings using the explode and implode functions Split and merge strings using the explode and implode functions Jun 15, 2023 pm 08:42 PM

In PHP programming, processing strings is a frequently required operation. Among them, splitting and merging strings are two common requirements. In order to perform these operations more conveniently, PHP provides two very practical functions, namely the explode and implode functions. This article will introduce the usage of these two functions, as well as some practical skills. 1. The explode function The explode function is used to split a string according to the specified delimiter and return an array. Its function prototype is as follows: arra

Common errors and solutions when using the explode function in PHP Common errors and solutions when using the explode function in PHP Mar 11, 2024 am 08:33 AM

Title: Common errors and solutions when using the explode function in PHP In PHP, the explode function is a common function used to split a string into an array. However, some common errors can occur due to improper use or incorrect data format. This article will analyze the problems you may encounter when using the explode function, and provide solutions and specific code examples. Mistake 1: The delimiter parameter is not passed in. When using the explode function, one of the most common mistakes is that the delimiter parameter is not passed in.

Split string into array using PHP function 'explode' Split string into array using PHP function 'explode' Jul 24, 2023 pm 11:09 PM

Use the PHP function "explode" to split a string into an array. In PHP development, you often encounter situations where you need to split a string according to the specified delimiter. At this time, we can use PHP's built-in function "explode" to convert string to array. This article will introduce how to use the "explode" function to split a string and give relevant code examples. The basic syntax of the "explode" function is as follows: arrayexplode(

Use PHP function 'explode' to split a string into multiple substrings Use PHP function 'explode' to split a string into multiple substrings Jul 25, 2023 pm 06:29 PM

Use the PHP function "explode" to split a string into multiple substrings. In PHP programming, we often encounter situations where we need to split a string into multiple substrings. At this time, PHP provides a very convenient function "explode" that can help us easily implement this function. The syntax of the "explode" function is as follows: arrayexplode(string$delimiter,string$string[,in

What should I do if php explode reports an error? What should I do if php explode reports an error? Jan 18, 2023 am 10:13 AM

Solution to php explode error: 1. Find and open the erroneous PHP code; 2. Find the explode function part; 3. Modify the code to "dump(explode(',',$str));die;", that is, use Just comma-separate the array.

How to use explode function to split string in PHP How to use explode function to split string in PHP Jun 26, 2023 pm 12:03 PM

In the PHP language, there are many basic functions that can help us process strings quickly and efficiently. Among them, the explode function is a very practical string splitting function. It can split a string into arrays according to the specified delimiter, and then perform more flexible string operations. In this article, we will introduce how to use the explode function to split strings in PHP. 1. The format of the explode function. The format of the explode function in the PHP language is as follows: explode(separa

What is the explode() function in PHP? What is the explode() function in PHP? Sep 04, 2023 pm 01:01 PM

In this article, learn how to use the PHPExplode() function, which is a predefined built-in PHP function. The explode function is used to "Split a string into smaller contents. The explode function in PHP enables us to break a string into smaller contents by breaking. This delimiter is called a delimiter. Syntax explode(delimiter, string, Number of elements) Parameter explosion function accepts three parameters, two of which are mandatory and one is optional. Let us discuss these three parameters. Separator This character specifies the critical point or point at which the string will be split, i.e. Whenever this character is found in a string, it symbolizes the end of one element and the beginning of another element in the array. String input string

See all articles