test example
$str='<div><p>here is the p tag</p><img src="" alt="here is the img tag"><a href="">here is the a tag</a><br ></div>';
1. Delete all or keep the specified html tags
The function strip_tags
that comes with php can meet the requirements
echo strip_tags($str,'<p><a>');
//Output: <p>here is the p tag</p><a href="">here is the a tag</a>
2. Delete the specified html tag
How to use: strip_html_tags($tags,$str)
<?php
function strip_html_tags($tags, $str)
{
$html = array();
foreach ($tags as $tag) {
$html[] = "/(<(?:\/" . $tag . "|" . $tag . ")[^>]*>)/i";
}
$data = preg_replace($html, '', $str);
}
echo strip_html_tags(array('p','img'),$str);
//Output: <div>here is the p tag <a href="">here is the a tag</a><br></div>;
3. Remove tags and tag content
How to use: strip_html_tags($tags,$str)
<?php
function strip_html_tags($tags,$str){
$html=array();
foreach ($tags as $tag) {
$html[]='/(<'.$tag.'.*?>[\s|\S]*?<\/'.$tag.'>)/';
}
$data=preg_replace($html,'',$str);
}
echo strip_html_tags(array('a','img'),$str);
//output <div><p>here is the p tag</p><img src="" alt="here is the img tag"><br></div>;
4. Delete the specified tag; delete or retain the content in the tag
How to use: strip_html_tags($tags,$str,$content)
<?php
/**
* Delete the specified tags and content
* @param array $tags array of tags to delete
* @param string $str data source
* @param string $content Whether to delete the content in the tag, the default is 0 to keep the content, 1 to not keep the content
* @return string
*/
function strip_html_tags($tags,$str,$content=0){
if($content){
$html=array();
foreach ($tags as $tag) {
$html[]='/(<'.$tag.'.*?>[\s|\S]*?<\/'.$tag.'>)/';
}
$data=preg_replace($html,'',$str);
}else{
$html=array();
foreach ($tags as $tag) {
$html[]="/(<(?:\/".$tag."|".$tag.")[^>]*>)/i";
}
$data=preg_replace($html, '', $str);
}
return $data;
}
echo strip_html_tags(array('a'),$str,1);
//output <div><p>here is the p tag</p><img src="" alt="here is the img tag"><br></div>;
?>
Post comment 取消回复