PHP 2 ways to remove a trailing space

Source: Internet
Author: User

This article mainly introduced the PHP to remove the 2 methods of the trailing space, this article has given the preg_replace substitution, the trim function two kinds of methods and has given the example, needs the friend to be possible to refer to under

Seemingly very simple problem, in fact, is still a bit of a pit, first of all, here is the space escape, not a string, directly with the trim () is not go away.

1, replace with Preg_replace

The code is as follows:
$test = "Dfadad on the relationship between the Sanying and the People" 775FD ";
$test = Preg_replace ('/^ (|s) *| (|s) *$/', ', $test);
Var_dump ($test);

The results are as follows:

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


This method is provided by the small partners within the group and is appreciated here. This method is recommended for generality

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 to find, if it is UTF8 code, with this method, no problem. If gbk,gb2312, there will be garbled. There is also the Json_encode, this function if it is gbk,gb2312, the Chinese character will be replaced with NULL. It is recommended to use UTF8 encoding.

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.