首頁  >  文章  >  後端開發  >  php如何去除html,空格,換行,提取純文字

php如何去除html,空格,換行,提取純文字

coldplay.xixi
coldplay.xixi原創
2020-08-17 09:18:232487瀏覽

php去除html,空格,換行,提取純文字的方法:1、清除字串兩邊的空格,程式碼為【$str = trim($str)】;2、匹配html中的空格,程式碼為【$str = preg_replace("/  /","",$str)】。

php如何去除html,空格,換行,提取純文字

php移除html,空格,換行,提取純文字的方法:

方法一:

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

呼叫方法

DeleteHtml($str);   

$str 為需要清除的頁面字符字串

方法二:

function DeleteHtml($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程式設計(影片)

#

以上是php如何去除html,空格,換行,提取純文字的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn