PHP source code explode usage instructions_PHP tutorial
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.
//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 php_explode_negative_limit(&zdelim, &zstr, return_value, limit);
} else {
add_index_stringl(return_value, 0, str, str_len, 1);
}
}
Copy code
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
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
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 add_next_index_stringl(return_value, p1, endp-p1, 1);
}
}
#define EXPLODE_ALLOC_STEP 64
char *p1, *p2, *endp;
*/
} 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 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:
//File 4: zend/zend_API.c
ZEND_API int add_next_index_stringl(zval *arg, const char *str, uint length, int duplicate) /* {{{ */
{
#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)

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools