Home > Backend Development > PHP Tutorial > PHP function to delete left and right spaces

PHP function to delete left and right spaces

高洛峰
Release: 2016-11-29 11:26:23
Original
1059 people have browsed it

The deletion function in PHP is much more specific than that in JS. In addition to the trim() function, there are also the ltrim() and rtrim() functions. They need to delete the left and right spaces respectively. In addition to these three functions, you can also use regular deletion.

ltrim() function: ltrim($str, $charlist)

$str represents the string being processed, $charlist is the special character to be deleted, if it is empty, the space at the left end will be removed, the code is as follows:

< ;?php

$t=" ...I'm Jacky...";

echo "a" .$t ."
";

$left=ltrim($t);

echo "a" .$left ."
";

$lleft=ltrim($left,".");

echo $lleft;

?>

rtrim() function: rtrim ($str, $charlist)

$str represents the string being processed. $charlist is the special character to be deleted. If it is empty, the space at the right end will be removed. The code is as follows:

$a= "htm ";

echo $a ."l" ."
";

echo rtrim($a) ."l";

?>

trim() function, first remove the head and tail Space, the code is as follows:

$str = ” This line containsstliberal rn use of whitespace.nn”;

// First remove the leading and trailing spaces

$str = trim($str);

// Then remove the two Above the space

$str = preg_replace('/s(?=s)/', '', $str);

// Finally, replace the non-space with a space

$str = preg_replace('/[ nrt]/', ' ', $str);

Use the above example to remove all extra spaces. First use TRim() to remove leading and trailing spaces, and then use preg_replace() to remove repeated spaces.

Use regular expressions Formula replacement, more powerful, php removes spaces at the beginning and end of the string (including full-width), the code is as follows:

$str=" phpfans网www.phpfensi.com   ";

$str = mb_ereg_replace(( '^( | )+', '', $str);

$str = mb_ereg_replace('(| )+$', '', $str);

echo mb_ereg_replace(' ', "n ", $ str);

?>


Related labels:
php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template