Php two ways to remove leading and trailing spaces _ PHP Tutorial

Source: Internet
Author: User
Php removes leading and trailing spaces. Two methods for removing leading and trailing spaces in php this article mainly introduces two methods for removing leading and trailing spaces in php. This article provides two methods, preg_replace and trim functions, and provides examples, two methods for removing leading and trailing spaces in php

This article mainly introduces two methods for removing spaces at the beginning and end of php. This article provides two methods for replacing with preg_replace and trim functions and provides examples. For more information, see

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.

This article mainly introduces two methods for removing spaces at the beginning and end of php. This article provides two methods, preg_replace and trim functions, and provides examples...

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.