- 去除所有的html标签,但是保留内容
$html = '你好,我是coco.';
$html = preg_replace("/<[\/\!]*?[^<>]*?>/si", '', $html);
2. 去除指定html标签及内容
$html = '你好,我是coco.';
echo $html.PHP_EOL;
$tag = 'b';
$replace = [];
$replace[] = '/<' . $tag . '.*?>[\s|\S]*?<\/' . $tag . '>/';
$replace[] = '/<' . $tag . '.*?>/';
$html = preg_replace($replace, '', $html);
echo $html;
- 修改html标记
$html = '你好,我是coco.';
echo $html.PHP_EOL;
$html = replaceTag($html,'b','span');
echo $html;
function replaceTag($content,$oldTag,$newTag)
{
return preg_replace('/<'.$oldTag.'>'.'(.*)'.'<\/'.$oldTag.'>'.'/U','<'.$newTag.'>'.'$1'.'.$newTag.'>',$content);
}
4. 匹配所有的含有标点符号的英语单词
$text_mark = 'I wonder what life was like here in the past. I really enjoyed walking around the town.';
$text_mark = preg_replace_callback('/[a-z]{1,}[\'\-\.\!\,\"\?]{1,}/i',function($match){
return ''.$match[0].'';
},$text_mark);
5. 匹配html中所有斜体的字母
function handleFont($html) {
$html = preg_replace_callback('/(.*)<\/span>/isU',function($matches){
if(strpos($matches[1],'font-style:italic;') !== false){
$text = $matches[2];
$chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','A','B','C','D','E','F','G'.'H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z','+','-','=','0','1','2','3','4','5','6','7','8','9'];
$preg = '/['.implode('',$chars).']+/isu';
$text = preg_replace_callback($preg,function($matches){
$chars = $matches[0];
return ''.$chars.'';
},$text);
return '.$matches[1].'">'.$text.'';
}else{
return $matches[0];
}
}, $html);
return $html;
}