PHP默認的函數有移除指定html標籤,名稱為strip_tags,在某些場合非常有用。
strip_tags
(PHP 3 >= 3.0.8, PHP 4, PHP 5)
strip_tags — Strip HTML and PHP tags from a string
string strip_tags ( string str [, string allowable_tags] )
弊端 :
這個函數只能保留想要的html標籤,就是參數string allowable_tags。
這個函數的參數allowable_tags的其他的用法。
strip_tags($source, 」); 去掉所以的html標籤。
strip_tags($source, 『<div><img><em>』); 保留字元串中的div、img、em標籤。
如果想去掉的html的指定標籤。那麼這個函數就不能滿足需求了。於是乎我用到了這個函數。
/**
* Removes specific tags.
*/
function strip_only_tags($str, $tags, $stripContent = FALSE) {
$content = ”;
if (!is_array($tags)) {
$tags = (strpos($str, ‘>’) !== false ? explode(‘>’, str_replace(‘<‘, ”, $tags)) : array($tags));
if (end($tags) == ”) {
array_pop($tags);
}
}
foreach($tags as $tag) {
if ($stripContent) {
$content = ‘(.+<!–‘.$tag.'(–>|\s[^>]*>)|)’;
}
$str = preg_replace(‘#<!–?’.$tag.'(–>|\s[^>]*>)’.$content.’#is’, ”, $str);
}
return $str;
}
參數說明
$str — 是指需要過濾的一段字元串,比如div、p、em、img等html標籤。
$tags — 是指想要移除指定的html標籤,比如a、img、p等。
$stripContent = FALSE — 移除標籤內的內容,比如將整個鏈接刪除等,默認為False,即不刪除標籤內的內容。
使用說明
$target = strip_only_tags($source, array(『a』,’em』,’b』));
移除$source字元串內的a、em、b標籤。
$source='<div><a href=”http://www.tsingyaun.cn” target=”_blank”><img src=”http://www.tsingyuan.cn/logo.png” border=”0″ alt=”Welcome to linzl.” />This a example from<em>lixiphp</em></a><strong>!</strong></div>
‘;
$target = strip_only_tags($source, array(‘a’,’em’));
//target results
//<div><img src=”http://blog.lixiphp.com/logo.png” border=”0″ alt=”Welcome to lixiphp.” />This a example from<strong>!</strong></div>
:left;”
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/255268.html