Home Backend Development PHP Tutorial PHP source code explode usage instructions_PHP tutorial

PHP source code explode usage instructions_PHP tutorial

Jul 21, 2016 pm 03:25 PM
explode php Instructions for use Split character us array Source code conduct

When we need to split an array into arrays based on a certain character or string, explode is very happy, but do you know how ~explode works~~
First of all, it is certain that explode can also be used Allocating space, no doubt.

Copy code The code is as follows:

//File 1: ext/standard/string.c
//First Let’s take a look at the source code of explode
PHP_FUNCTION(explode)
{
char *str, *delim;
int str_len = 0, delim_len = 0;
long limit = LONG_MAX; /* No limit */
zval zdelim, zstr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &delim, &delim_len, &str, &str_len, &limit) == FAILURE) {
return;
}
if (delim_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty delimiter");
RETURN_FALSE;
}
//An array will be opened here , used to store divided data
array_init(return_value);
//Because of this, we use explode('|', ''); to become legal
if (str_len == 0) {
if (limit >= 0) {
add_next_index_stringl(return_value, "", sizeof("") - 1, 1);
}
return;
}
//The following two construct the original string and delimiter into a _zval_struct structure.
//ZVAL_STRINGL will allocate space~~The source code will be posted later
ZVAL_STRINGL(&zstr, str, str_len, 0 ; {
php_explode(&zdelim, &zstr, return_value, limit);
} else if (limit < 0) {
php_explode_negative_limit(&zdelim, &zstr, return_value, limit);
} else {
add_index_stringl(return_value, 0, str, str_len, 1);
}
}




Copy code
The code is as follows : //Source code of ZVAL_STRINGL:
//File 2: zend/zend_API.c
#define ZVAL_STRINGL(z, s, l, duplicate) {
const char *__s=(s); int __l=l;
Z_STRLEN_P(z) = __l;
Z_STRVAL_P(z) = (duplicate?estrndup(__s, __l):(char*)__s);
Z_TYPE_P(z) = IS_STRING;
}
....
//estrndup is the main course:
//File 3: zend/zend_alloc.h
#define estrndup( s, length) _estrndup((s), (length) ZEND_FILE_LINE_CC ZEND_FILE_LINE_EMPTY_CC)
....
//Implementation of _estrndup: zend/zend_alloc.c
ZEND_API char *_estrndup(const char *s, uint length ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
{
char *p;
p = (char *) _emalloc(length+1 ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
if (UNEXPECTED(p == NULL)) {
return p;
}
memcpy(p, s, length); //Allocate space
p[length] = 0;
return p;
}
//Also ZVAL_STRING used in substr and strrchr strstr also uses the implementation of appeal


The following is to analyze the call based on the third parameter limit of explode: the condition corresponds to the last three lines in explode, for Differences in limit conditions
Note: When limit is defaulted (not passed), its default value is LONG_MAX, which is the case of branch 1
1, limit > 1:
Call the php_explode method , this method can also be found in ext/standard/string.c, and appears immediately above the explode implementation (so it is very convenient to find the method calling from this file in this function, almost all except one column are in The function is immediately above ^_^),



Copy code
The code is as follows:

PHPAPI void php_explode(zval *delim, zval *str, zval *return_value, long limit)
{
char *p1, *p2, *endp;
//Get it first It is the pointer to the end position of the source string
endp = Z_STRVAL_P(str) + Z_STRLEN_P(str);
//Record starting position
p1 = Z_STRVAL_P(str);
//The following is Get the position of the separator in str. You can see that this method is also used in strrpos and strpos to locate
p2 = php_memnstr(Z_STRVAL_P(str), Z_STRVAL_P(delim), Z_STRLEN_P(delim), endp);
if (p2 == NULL) {
//Because of this, when we call explode('|', 'abc'); it is legal, and what comes out is array(0 => 'abc' )
add_next_index_stringl(return_value, p1, Z_STRLEN_P(str), 1);
} else {
//Loop to obtain the position of the next delimiter in sequence until the end
do {
/ /The obtained substring (the section between the previous position and this position, the previous position is the beginning for the first time
add_next_index_stringl(return_value, p1, p2 - p1, 1);
//Positioning To the delimiter position p2 + the length of the delimiter
//For example, delimiter ='|', original string = 'ab|c', p2 = 2, then p1=2+1=3
p1 = p2 + Z_STRLEN_P(delim);
} while ((p2 = php_memnstr(p1, Z_STRVAL_P(delim), Z_STRLEN_P(delim), endp)) != NULL &&
--limit > 1);
//Put the string after the last delimiter into the result array
//explode('|', 'avc|sdf'); => array(0 => 'avc' , 1= > 'sdf')
if (p1 <= endp)
add_next_index_stringl(return_value, p1, endp-p1, 1);
}
}
<0 php_explode_negative_limit(zval *delim, zval *str, zval *return_value, long limit)
{
#define EXPLODE_ALLOC_STEP 64
char *p1, *p2, *endp;
endp = Z_STRVAL_P(str) + Z_STRLEN_P(str); p1 = Z_STRVAL_P(str); p2 = php_memnstr(Z_STRVAL_P(str), Z_STRVAL_P(delim), Z_STRLEN_P(delim), endp); if (p2 == NULL ) { //It is not processed here, then explode('|', 'abc', -1) becomes illegal and cannot get any value
/*
do nothing since limit < ;= -1, thus if only one chunk - 1 + (limit) <= 0
by doing nothing we return empty array
*/
} else {
int allocated = EXPLODE_ALLOC_STEP, found = 0;
long i, to_return;
char **positions = emalloc(allocated * sizeof(char *));
//Note the declaration of positions here, this array is used to save all sub- The reading position of the string
positions[found++] = p1; //Of course the starting position still needs to be saved
//The following two loops, the first one is to loop through all delimiter positions that appear in the string , and save the next substring reading position
do {
if (found >= allocated) {
allocated = found + EXPLODE_ALLOC_STEP;/* make sure we have enough memory */
positions = erealloc(positions, allocated*sizeof(char *));
}
positions[found++] = p1 = p2 + Z_STRLEN_P(delim);
} while ((p2 = php_memnstr(p1, Z_STRVAL_P(delim), Z_STRLEN_P(delim), endp)) != NULL);
//This is the substring from which the returned result will be read from the array
to_return = limit + found;
/* limit is at least -1 therefore no need of bounds checking : i will be always less than found */
for (i = 0;i < to_return;i++) { /* this checks also for to_return > 0 */
add_next_index_stringl(return_value, positions[i],
(positions[i+1] - Z_STRLEN_P(delim)) - positions[i],
1
);
}
efree(positions); // Very important, release memory
}
#undef EXPLODE_ALLOC_STEP
}


3. limit = 1 or limit = 0 :
When all the first and second conditions are not met, this branch will be entered. This branch is simply to put the source string into the output array, explode('|', 'avc|sd' , 1) or explode('|', 'avc|sd', 0) will return array(0 => 'avc|sd');



Copy code

The code is as follows:

//add_index_stringl source code
//File 4: zend/zend_API.c
ZEND_API int add_next_index_stringl(zval *arg, const char *str, uint length, int duplicate) /* {{{ */
{
zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); }
//zend_hash_next_index_insert
//zend/zend_hash.h
#define zend_hash_next_index_insert(ht, pData, nDataSize .

Visible (excluding allocated space),
When limit>1, the efficiency is O(N) [N is the limit value],
When limitWhen limit=1 or limit=0, the efficiency is O(1)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324052.htmlTechArticleWhen we need to split an array into arrays based on a certain character or string, explode is very useful happy, but do you know~how explode works~~ First of all, you can be sure...
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles