PHP 2 ways to remove leading and trailing spaces _php tutorial

Source: Internet
Author: User

PHP 2 ways to remove kinsoku and trailing spaces


This article mainly introduces the PHP 2 ways to remove the leading and trailing spaces, this paper gives the use of preg_replace replacement, trim function two methods and give an example, the need for friends can refer to the following

Seemingly simple question, in fact, there is a bit of a pit, the first place to escape the space, not a string, directly with trim () is not to go off.

1, replace with Preg_replace

The code is as follows:


$test = "Dfadad on the relationship between the Sanying and the responsible people 775FD";
$test = Preg_replace ('/^ (|\s) *| (|\s) *$/', ', $test);
Var_dump ($test);

The results are as follows:

String ' Dfadad on the relationship between the responsible people and Sanying 775FD ' (length=35)


This method is provided by the small partners inside the group, which expresses thanks. Recommend this method, with versatility

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 results are as follows:

String ' Dfadad 3333adf775fd ' (length=19)


This method is from the official PHP manual, if it is UTF8 code, using this method, there is no problem. If gbk,gb2312, it will appear garbled. There is also the json_encode, if this function is gbk,gb2312, the Chinese characters will be replaced with NULL. It is recommended to use UTF8 encoding.

http://www.bkjia.com/PHPjc/968658.html www.bkjia.com true http://www.bkjia.com/PHPjc/968658.html techarticle PHP 2 Ways to remove the leading and trailing spaces this article mainly introduces the PHP 2 ways to remove the top and tail space, this paper gives the use of preg_replace replacement, trim function two methods and give an example, need ...

  • 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.