php如何清除html格式並去除文字中的空格然後截取文字,詳細分享一下處理方法(順便對PHP清除HTML字符串的函數做了一個小結):
htmlspecialchars 將特殊字元轉成 HTML
格式語法: string htmlspecialchars(string string);
傳回值: 字串
函式種類: 資料處理
內容說明 本函式將特殊字元轉成 HTML 的字串格式 ( &....; )。
最常用到的場合可能就是處理客戶留言的留言版了。
& (和) 轉成 &
" (雙引號) 轉成 "
< (小於) 轉成 <
> (大於) 轉成 >
此函式只轉換上面的特殊字元,並不會全部轉換成 HTML 所定的 ASCII 轉換。
htmlentities 將所有的字元都轉成 HTML 字串
語法: string htmlentities(string string);
傳回值: 字串
函式種類: 資料處理
內容說明 本函式有點像 htmlspecialchars() 函式,但本函式會將所有 string 的字元都轉成 HTML的特殊字集字串。不過在轉換後閱讀網頁原始碼的方面,會有很多困擾,尤其是網頁原始碼的中文字會變得不知所云,瀏覽器上看到的還是正常的。
strip_tags($str) 去掉 HTML 及 PHP 的標記語法: string strip_tags(string str); 傳回值: 字串 函式種類: 資料處理 內容說明 :本函式可去掉字串中包含的任何 HTML 及 PHP 的標記字串。若是字串的 HTML 及 PHP 標籤原來就有錯,例如少了大於的符號,則也會傳回錯誤。
PHP去除html、css樣式、js格式的方法很多,但根據經驗發現,它們基本都有一個弊端:基本都清除不掉文字中包含的空格或者tab鍵,經過不斷的探索,終於找到了一個理想的去除html字符並且能夠去除空格,css樣式和js 的PHP函數。
PHP清除html、css、js格式並去除空格的PHP函數
01 |
function cutstr_html( $string , $length =0, $ellipsis = '…' ){ |
02 |
$string = strip_tags ( $string ); |
03 |
$string =preg_replace( '/\n/is' , '' , $string ); |
04 |
$string =preg_replace( '/
| /is' , '' , $string ); |
05 |
$string =preg_replace( '/ /is' , '' , $string ); |
06 |
preg_match_all( "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/" , $string , $string ); |
07 |
if ( is_array ( $string )&&! empty ( $string [0])){ |
08 |
if ( is_numeric ( $length )&& $length ){ |
09 |
$string =join( '' , array_slice ( $string [0],0, $length )). $ellipsis ; |
11 |
$string =implode( '' , $string [0]); |
php 去除html標籤 js 和 css樣式
01 |
function clearHtml( $content ){ |
02 |
$content =preg_replace( "/<a[^>]*>/i" , "" , $content ); |
03 |
$content =preg_replace( "/<\/a>/i" , "" , $content ); |
04 |
$content =preg_replace( "/<div[^>]*>/i" , "" , $content ); |
05 |
$content =preg_replace( "/<\/div>/i" , "" , $content ); |
06 |
$content =preg_replace( "/<!--[^>]*-->/i" , "" , $content ); |
07 |
$content =preg_replace( "/style=.+?['|\"]/i" ,'', $content ); |
08 |
$content =preg_replace( "/class=.+?['|\"]/i" ,'', $content ); |
09 |
$content =preg_replace( "/id=.+?['|\"]/i" ,'', $content ); |
10 |
$content =preg_replace( "/lang=.+?['|\"]/i" ,'', $content ); |
11 |
$content =preg_replace( "/width=.+?['|\"]/i" ,'', $content ); |
12 |
$content =preg_replace( "/height=.+?['|\"]/i" ,'', $content ); |
13 |
$content =preg_replace( "/border=.+?['|\"]/i" ,'', $content ); |
14 |
$content =preg_replace( "/face=.+?['|\"]/i" ,'', $content ); |
15 |
$content =preg_replace( "/face=.+?['|\"]/" ,'', $content ); |