如何将PHP代码中的空格和换行符全部去除?

2026-04-06 17:501阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计495个文字,预计阅读时间需要2分钟。

如何将PHP代码中的空格和换行符全部去除?

PHP清除空格换行的方法:

1.使用function clearHtml($str) {...}函数清除;

2.使用strip_tags()函数去除;

3.使用正则表达式清除。

php清除空格换行的方法:1、通过“function clearHtml($str){...}”方法清除;2、通过“strip_tags()”函数去除;3、通过正则表达式清除。

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php怎么清除空格换行?

PHP去除字符串空格与换行html标记

方法一

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); //返回字符串 }

方法二:

strip_tags() 函数剥去 HTML、XML 以及 PHP 的标签。

strip_tags() 函数官方介绍: www.php.net/manual/zh/function.strip-tags.php

加入到上面的方法中去。

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); //返回字符串 }

方法三:正则表达式

去除字符串内部的空行:

$str = preg_replace("/(s*?r?ns*?)+/","n",$str);

去除全部的空行,包括内部和头尾:

$str = preg_replace('/($s*$)|(^s*^)/m', '',$str);

以上三种方法,可以 去除PHP字符串空格与换行html标记。

推荐学习:《PHP视频教程》

以上就是php怎么清除空格换行的详细内容,更多请关注自由互联其它相关文章!

如何将PHP代码中的空格和换行符全部去除?

本文共计495个文字,预计阅读时间需要2分钟。

如何将PHP代码中的空格和换行符全部去除?

PHP清除空格换行的方法:

1.使用function clearHtml($str) {...}函数清除;

2.使用strip_tags()函数去除;

3.使用正则表达式清除。

php清除空格换行的方法:1、通过“function clearHtml($str){...}”方法清除;2、通过“strip_tags()”函数去除;3、通过正则表达式清除。

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php怎么清除空格换行?

PHP去除字符串空格与换行html标记

方法一

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); //返回字符串 }

方法二:

strip_tags() 函数剥去 HTML、XML 以及 PHP 的标签。

strip_tags() 函数官方介绍: www.php.net/manual/zh/function.strip-tags.php

加入到上面的方法中去。

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); //返回字符串 }

方法三:正则表达式

去除字符串内部的空行:

$str = preg_replace("/(s*?r?ns*?)+/","n",$str);

去除全部的空行,包括内部和头尾:

$str = preg_replace('/($s*$)|(^s*^)/m', '',$str);

以上三种方法,可以 去除PHP字符串空格与换行html标记。

推荐学习:《PHP视频教程》

以上就是php怎么清除空格换行的详细内容,更多请关注自由互联其它相关文章!

如何将PHP代码中的空格和换行符全部去除?