我們要過濾html標簽或字符串中指定的html標簽我們可以利用php正則來實現(xiàn),下面的三個例子我們一起來看看吧.
1.正則過濾指定標簽,代碼如下:
- /**
- * @param $content
- * @return mixed
- * 過濾a標簽保留內(nèi)容
- */
- public function delete_tags_a($content){
- $content = preg_replace("#<a[^>]*>(.*?)</a>#is", "$1", $content);
- return $content;
- }
2.過濾所有html標簽內(nèi)容,代碼如下:
- /**
- * @param $content
- * @param string $tag 傳入要刪除的標簽
- * @param bool $ident true 保留標簽內(nèi)容,false不保留標簽內(nèi)容
- * @return mixed
- */
- public function delete_tags($content,$tag='a',$ident=true){
- if($ident){ //開源軟件:Vevb.com
- $content = preg_replace("#<{$tag}[^>]*>(.*?)</{$tag}>#is", "$1", $content);
- }else{
- $content = preg_replace("/(<$tag.*?>[\s\S]*?<\/$tag>)/",'',$content);
- }
- return $content;
- }
3.代碼如下:
- /**
- * @param $str
- * @return mixed|string
- * 過濾所有html標簽
- */
- public function deletehtml($str)
- {
- $str = trim($str);
- $str=strip_tags($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);
- return $str;
- }
當然還有一些php函數(shù)可以直接過濾,他會過濾除了字符串之外的所有html標簽,這個函數(shù)我就不介紹了.
新聞熱點
疑難解答