Trim(), preg_replace() in php to clear string spaces and consecutive spaces_PHP tutorial

WBOY
Release: 2016-07-13 16:56:57
Original
1164 people have browsed it

The simplest way to clear spaces in PHP is to use the trim() function, but this function often cannot achieve the results we want, especially when the string contains characters like \r\n, it cannot be produced. Yes, below I introduce a perfect method to solve this problem.

//Remove the starting and ending whitespace
$str = trim($str);
The code is as follows
 代码如下 复制代码

$str = " This line containstliberal rn use of whitespace.nn";

//去掉开始和结束的空白
$str = trim($str);

//去掉跟随别的挤在一块的空白
$str = preg_replace('/s(?=s)/', '', $str);

//最后,去掉非space 的空白,用一个空格代替
$str = preg_replace('/[nrt]/', ' ', $str);

echo "

{$str}
";

?>

Copy code

$str = "This line containsliberal rn use of whitespace.nn";

//Remove the white space that is crowded with others
$str = preg_replace('/s(?=s)/', '', $str);

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

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!