Example of a PHP replacement that filters all whitespace characters and spaces

Source: Internet
Author: User

In PHP, the TRIM function can only replace the left and right sides of the space, feeling in some cases not very good, if you want to be a string of all white space characters filter out (spaces, full-width spaces, newline, etc.), then we can write a filter function.

PHP Learning Str_replace functions are known, can be batch replacement, so we can use the following source code implementation to replace filter a string of all white-space characters.

PHP Source Reference:

<?php
$str = ' Jkgsd
Gsgsdgs GSDG GSD ';
echo Mytrim ($STR);
function Mytrim ($STR)
{
$search = Array ("", "", "\ n", "\ r", "T");
$replace = Array ("", "", "", "", "");
Return Str_replace ($search, $replace, $STR);
}
?>

Run code, page output: JKGSDGSGSDGSGSDGGSD, perfect to achieve the effect we want.

To do this, you can use a regular expression of PHP to complete the

The following example can remove the extra whitespace

<?php

$STR = "This line contains\tliberal \ r \ n whitespace.\n\n";

The leading/trailing whitespace

Remove the start and end blanks

$str = Trim ($STR);

Now remove any doubled-up whitespace

To take the rest of the space and squeeze it in.

$str = Preg_replace ('/\s (? =\s)/', ', $str);


Finally, replace any non-space whitespace and a space

Finally, remove the blank space, using a space instead

$str = preg_replace ('/[\n\r\t]/', ', ', $str);

Echo out: ' This line contains liberal the use of whitespace. '

echo "<pre>{$str}</pre>";

?>

This example strips out the extra whitespace characters

<?php
$str = ' foo o ';
$str = preg_replace ('/\s\s+/', ', ', $str);
will be changed to ' foo o '
Echo $str;
?>

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.