Home > Backend Development > PHP Problem > How to clear spaces and line breaks in php

How to clear spaces and line breaks in php

藏色散人
Release: 2023-03-11 07:16:01
Original
3144 people have browsed it

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 .

How to clear spaces and line breaks in php

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

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

Method 3: Regular expression

Remove blank lines inside the string:

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

Remove all blank lines, including the inside and the beginning and the end:

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

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!

Related labels:
php
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