php method to clear spaces and line breaks: 1. Clear through the "function clearHtml($str){...}" method; 2. Remove through the "strip_tags()" function; 3. Clear through regular expressions .
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
How to clear spaces and line breaks in php?
PHP removes string spaces and line breaks html tags
Method one
function clearHtml($str) { $str = trim($str); //清除字符串两边的空格 $str = preg_replace("/\t/","",$str); //使用正则表达式替换内容,如:空格,换行,并将替换为空。 $str = preg_replace("/\r\n/","",$str); $str = preg_replace("/\r/","",$str); $str = preg_replace("/\n/","",$str); $str = preg_replace("/ /","",$str); $str = preg_replace("/ /","",$str); //匹配html中的空格 return trim($str); //返回字符串 }
Method two:
strip_tags() function strips HTML, XML and PHP Tag of.
strip_tags() function official introduction: http://www.php.net/manual/zh/function.strip-tags.php
Add to the above method.
function ClearHtml($str) { $str = trim($str); //清除字符串两边的空格 $str = strip_tags($str,""); //利用php自带的函数清除html格式 $str = preg_replace("/\t/","",$str); //使用正则表达式替换内容,如:空格,换行,并将替换为空。 $str = preg_replace("/\r\n/","",$str); $str = preg_replace("/\r/","",$str); $str = preg_replace("/\n/","",$str); $str = preg_replace("/ /","",$str); $str = preg_replace("/ /","",$str); //匹配html中的空格 return trim($str); //返回字符串 }
Method 3: Regular expression
Remove blank lines inside the string:
$str = preg_replace("/(s*?r?ns*?)+/","n",$str);
Remove all blank lines, including the inside and the beginning and the end:
$str = preg_replace('/($s*$)|(^s*^)/m', '',$str);
The above three methods can remove spaces and newline html tags in PHP strings.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to clear spaces and line breaks in php. For more information, please follow other related articles on the PHP Chinese website!