PHP trim (), preg_replace () clear string spaces and contiguous spaces _php Tutorial

Source: Internet
Author: User
The simplest way to clear a space in PHP is to use the trim () function, but this function is often not up to the result we want, especially if the string has characters like \\r\\n that cannot be made, and here's a perfect solution to this problem.
The code is as follows Copy Code

$STR = "This line containstliberal RN use of whitespace.nn";

Remove the opening and closing blanks
$str = Trim ($STR);

Remove the blank that follows the other squeeze
$str = Preg_replace ('/s (? =s)/', ' ', $str);

Finally, remove the non-space space, with a space instead
$str = preg_replace ('/[nrt]/', ' ', $str);

echo "

{$STR}
";

?>

The previous example removes all the blanks step-by-step. First we use the trim () function to remove the opening and closing blanks. Then we use Preg_replace () to remove the duplicates. s stands for any whitespace. (? =) indicates a forward lookup. It tastes like a character that matches only the characters that follow the same character as itself. So the regular expression means: "Any whitespace character followed by the whitespace character." "We replace them with blanks, so we remove them, leaving the only whitespace characters."

Finally, we use another regular expression [NRT] to find any remaining newline characters (n), carriage return (r), or tab (t). We replace these with a space.

http://www.bkjia.com/PHPjc/631568.html www.bkjia.com true http://www.bkjia.com/PHPjc/631568.html techarticle The simplest way to clear a space in PHP is to use the trim () function, but this function is often not up to the result we want, especially if the string has characters like \\r\\n that cannot be made ...

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