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.
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 starting and ending whitespace
$str = trim($str);
//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);
echo "{$str}
";
?>
The above example removes all the whitespace step by step. First we use the trim() function to remove the starting and ending whitespace. Then, we use preg_replace() to remove duplicates. s represents any whitespace. (?=) means look forward. It means that it only matches characters that are followed by the same character as itself. So this regex means: "Any whitespace character followed by a whitespace character." We replace it with whitespace, which removes it and leaves only the whitespace character.
Finally, we use another regular expression [nrt] to find any remaining newlines (n), carriage returns (r), or tabs (t). We replace these with a space.
http://www.bkjia.com/PHPjc/631568.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631568.htmlTechArticleThe easiest way to clear spaces in php is to use the trim() function, but this function often cannot reach us The desired result cannot be produced, especially when the string contains characters like \r\n...
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