Home >Backend Development >PHP Problem >How to replace whitespace in php

How to replace whitespace in php

藏色散人
藏色散人Original
2020-08-18 10:32:562210browse

How to replace whitespace in php: first remove the starting and ending whitespace through the "trim($str)" method; then use "preg_replace" to remove the whitespace that is crowded with others; finally use regular expressions to remove non-space blank and replace it with a space.

How to replace whitespace in php

Recommended: "PHP Video Tutorial"

php replaces and filters all whitespace characters and spaces Example

The trim function that comes with PHP can only replace the spaces at the left and right ends. I feel that it is not very useful in some cases. If you want to filter out all the whitespace characters in a string (spaces , full-width spaces, newlines, etc.), then we can write a filter function ourselves.

Everyone who has learned the str_replace function in php knows that it can be replaced in batches, so we can use the following source code to replace and filter all whitespace characters in a string.

php source code reference:

$str = 'jkgsd
gsgsdgs  gsdg gsd';
echo myTrim($str);
function myTrim($str)
{
 $search = array(" "," ","\n","\r","\t");
 $replace = array("","","","","");
 return str_replace($search, $replace, $str);
}
?>
运行代码,页面输出:jkgsdgsgsdgsgsdggsd,完美实现了我们想要的效果。
完成这些可以使用PHP的正则表达式来完成
下例可以去除额外Whitespace
$str = " This line  contains\tliberal \r\n use of   whitespace.\n\n";
// First remove the leading/trailing whitespace
//去掉开始和结束的空白
$str = trim($str);
// Now remove any doubled-up whitespace
//去掉跟随别的挤在一块的空白
$str = preg_replace('/\s(?=\s)/', '', $str);
// Finally, replace any non-space whitespace, with a space
//最后,去掉非space 的空白,用一个空格代替
$str = preg_replace('/[\n\r\t]/', ' ', $str);
// Echo out: 'This line contains liberal use of whitespace.'
echo "
{$str}
";
?>
这个例子剥离多余的空白字符
$str = 'foo o';
$str = preg_replace('/\s\s+/', '', $str);
// 将会改变为'foo o'
echo $str;
?>

The above is the detailed content of How to replace whitespace in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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