- 去除所有的html标签,但是保留内容
$html = '你好,我是coco.
';
$html = preg_replace("/<[\/\!]*?[^<>]*?>/si", '', $html);
![常用正则表达式整理php_第1张图片](http://img.e-com-net.com/image/info8/f75fa29615e54854a9f0fd8cde8af559.jpg)
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;
![在这里插入图片描述](http://img.e-com-net.com/image/info8/a6c95e2fd0ad43c18fe785a046d477cc.jpg)
- 修改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);
}
![常用正则表达式整理php_第2张图片](http://img.e-com-net.com/image/info8/b6b93a570e204dd69811e8223909c023.jpg)
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);
![在这里插入图片描述](http://img.e-com-net.com/image/info8/f161612e827440bdbc3a22acf481817f.jpg)
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;
}
![常用正则表达式整理php_第3张图片](http://img.e-com-net.com/image/info8/c9305b038ac24ebc830c2ba5489b075f.jpg)