Php two ways to remove leading and trailing spaces, php header and trailing space 2 _ PHP Tutorial

Source: Internet
Author: User
Php removes the leading and trailing spaces, and php removes the trailing spaces. Php two methods to remove leading and trailing spaces. php two seemingly simple headers and trailing spaces are actually a bit pitfall. first, space escaping is not a string. trim () is used directly () is two ways to remove leading and trailing spaces without removing php, and two ways to remove leading and trailing spaces with php

The seemingly simple problem is actually a bit Pitfall. first, Space escape is not a string. trim () cannot be used directly.

1. replace with preg_replace
The code is as follows:
$ Test = "dfadad's relationship between the responsible people and Sanying 775fd ";
$ Test = preg_replace ('/^ (| \ s) * | (| \ s) * $/', '', $ test );
Var_dump ($ test );

// The result is as follows:

String 'dfadad on the relationship between the responsible persons and Sanying 775fd '(length = 35)

This method is provided by friends in the group, and I would like to express my gratitude. This method is recommended and Universal

2. trim method
The code is as follows:
$ Test = "dfadad 3333adf775fd ";
$ Test = trim (html_entity_decode ($ test), chr (0xc2). chr (0xa0 ));
Var_dump ($ test );

// The result is as follows:

String 'dfadad 3333adf775fd '(length = 19)

This method is found in the official php Manual. if it is UTF-8 encoded, it is okay to use this method. If it is GBK or GB2312, garbled characters will appear. There is also json_encode. if this function is gbk or gb2312, Chinese characters will be replaced with null. Utf8 encoding is recommended.

The trim seems very simple, but it is still a bit Pitfall. First, the space escape here is not a string, and trim () cannot be used directly...

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.