Clear all space program codes of strings in PHP

Source: Internet
Author: User

I first used trim () rtrim () ltrim () to delete spaces.

The code is as follows: Copy code

<? Php
Echo trim ("blank"). "<br> ";
Echo rtrim ("blank box"). "<br> ";
Echo ltrim ("space"). "<br> ";
?>

As a result, we did not want to delete any space in the middle. Later, we carefully checked the usage of the three functions.

Trim () removes spaces at both ends of a string,
Rtrim () removes the right space of a string,
Ltrim () is to remove the left space of a string.

It is clear that there is no ability to delete spaces in the middle. What should we do with Baidu? Some people have said that we should replace the function with regular expressions. Let's just give it a try.

Someone said this.

The code is as follows: Copy code

$ Str = "This line contains \ tliberal \ r \ n use of whitespace. \ n ";
$ Str = trim ($ str); // first remove the leading and trailing spaces
$ Str = preg_replace ('/\ s (? = \ S)/', '', $ str); // remove the two or more spaces
$ Str = preg_replace ('/[\ n \ r \ t]/', ', $ str); // replace a non-space with a space.

In the above example, we can remove all unnecessary spaces ..

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.