[PHP source code] trim, rtrim, and ltrim functions

Source: Internet
Author: User
Tags rtrim
[PHP source code reading] trim, rtrim, and ltrim functions trim series functions are used to remove spaces or other characters at the beginning and end of a string. The ltrim function removes only the first character of the string. the rtrim function only removes the character at the end of the string.

Trim

String trim (string $ str [, string $ character_mask = "\ t \ n \ r \ 0 \ x0B"])

Parameter description

Character_mask
The default value is "\ t \ n \ r \ 0 \ x0B" and other blank characters.

You can specify a range of characters. Note that the left and right sides of "..." are valid range values. if an invalid value is passed, an error is returned.

Running example

Let's take a look at the normal use:

$ Str = 'Hello .. '; $ new_str = trim ($ str,'. '); // The result is hello.

A strange result. Here, the error is reported because php regards the left and right sides of "..." as the range value, while the left side of "..." here is the character ".", and PHP considers it a range value without the right border.

$ Str = 'Hello ...';
$ Second_str = trim ($ str, '...'); // error

The second parameter uses valid boundary values:

$ Str = 'helloabcdefg'; $ new_str = trim ($ str, 'a .. G'); // output hello

Trim execution steps

Trim, ltrim, and rtrim are all called.Php_do_trimFunction, the difference is that the second parameter mode is different. This article mainly analyzes trim functions. the ltrim and rtrim functions are similar to trim functions. Then php_do_trim will callPhp_trimSo the core function of the trim function is the php_trim function. The procedure is as follows:

1. set the mask array to save the filter characters based on what values

2. filter the characters to be filtered in the string header

3. filter the characters to be filtered at the end of the string

The flowchart of php_trim function execution is as follows:

Source code explanation

The php_trim function first calls php_charmask. this function sets the filter character to the form of mask [char] = 1. this is a hash array and can be used for subsequent judgment. If the second parameter is a range value, the memset function is called to assign values to the mask array.

When we use the mode variable to determine which filter is used, there is a small optimization here. in PHP, we use an internal operation rather than multiple judgment conditions. The code is as follows:

    if (mode & 1) {        for (i = 0; i < len; i++) {            if (mask[(unsigned char)c[i]]) {                trimmed++;            } else {                break;            }        }        len -= trimmed;        c += trimmed;    }    if (mode & 2) {        for (i = len - 1; i >= 0; i--) {            if (mask[(unsigned char)c[i]]) {                len--;            } else {                break;            }        }    }

Judgment process:

1 & 1 = 1 left needs to be filtered
2 & 1 = 0. no filter is required on the left.
3 & 1 = 1 left needs to be filtered
1 & 2 = 0 do not need to be filtered
2 & 2 = 1 the right side needs to be filtered
3 & 2 = 1 the right side needs to be filtered


Using bitwise operations like this can improve program efficiency, and the code is more concise and easy to read.

Summary

Read the source code of this function. First, we learned that in C language, if you need to make a key-value pair array and the key value is a single character, you can use the unsigned char type as an array subscript, in this way, we can construct a map array with similar characters as the underlying object.

Second, bitwise operations can improve program efficiency and code readability.

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.

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. You can use the commit record to view the added annotations.

For more source code articles, visit the personal homepage for more information: hoohack

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.