常用正则表达式整理php

  1. 去除所有的html标签,但是保留内容
$html = '你好,我是coco.';
$html = preg_replace("/<[\/\!]*?[^<>]*?>/si", '', $html);

常用正则表达式整理php_第1张图片
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;

在这里插入图片描述

  1. 修改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张图片
4. 匹配所有的含有标点符号的英语单词

// 将标点符号与前面的单词放如一个span中防止换行
$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;
    }

常用正则表达式整理php_第3张图片

你可能感兴趣的:(正则表达式,php)