Yii2-WangEditorWidget上传以后数据库字段格式化

/**
 * 格式化正文中的图片路径,入库时替换为相对路径,获取详情时替换为绝对路径
 */
public function formatContent($content, $type = 'insert')
{
    $imgUrlPrefix = rtrim(Yii::$app->params['cdn_url_prefix'], '/');
    $urlData = parse_url($imgUrlPrefix);
    $host = $urlData['host'];
    $scheme = $urlData['scheme'];

    //过滤正文无用内容
    if($type == 'insert'){
        //过滤js脚本
        $pattern = "//i";
        $content = preg_replace($pattern, '', $content);
        //过滤样式
        $pattern = "//i";
        $content = preg_replace($pattern, '', $content);
        //除img标签外过滤掉标签的所有属性
        $pattern ="/<((?!img)[a-z][a-z0-9]*)[^>]*?(\/?)>/i";
        $content = preg_replace($pattern,'<$1$2>', $content);

        //过滤word中font标签
        $pattern = "/([\s\S]*?)<\/font>/i";
        $content = preg_replace($pattern, '$1', $content);
        //将单个font标签替换为空
        $pattern = "/<\/font>|/";
        $content = preg_replace($pattern, '', $content);

        //过滤word中xml数据
        $pattern = "//";
        $content = preg_replace($pattern, '', $content);

        //将单个div标签替换
        $pattern = "/<\/div>|/";
        $content = preg_replace($pattern, '', $content);

        //替换空p标签
        $pattern = "/


<\/p>|

<\/p>/"; $content = preg_replace($pattern, '', $content); //将没有任何标签的文本,用p标签包含 $pattern = "/<\/p>((?!

)[\s\S]+?)

/"; $content = preg_replace($pattern, "

$1

", $content); //将没有任何标签的文本,用p标签包含 $pattern = "/<\/p>((?!

)[\s\S]+?)$/"; $content = preg_replace($pattern, "

$1

", $content); //过滤掉其他无用标签 $content = strip_tags($content, '


'); } //处理图片,如果是外部图片,替换为空 $pattern = '//i'; if(preg_match_all($pattern, strip_tags($content,''), $matches) > 0) { if($type == 'insert'){ foreach($matches[1] as $key=>$value){ $urlInfo = parse_url($value); if($urlInfo['scheme']."://".$urlInfo['host'] == $scheme.'://'.$host){ $replace = str_replace($imgUrlPrefix, '', $matches[0][$key]); $content = str_replace($matches[0][$key], $replace, $content); }else{ $content = str_replace($matches[0][$key], '', $content); } } $content = preg_replace('/title\s*=\s*[\"|\'].*?[\"|\']/', '', $content); }elseif($type == 'detail'){ foreach($matches[1] as $value){ if(substr($value, 0 , 1) !== '/'){ $replace = $imgUrlPrefix.'/'.$value; }else{ $replace = $imgUrlPrefix.$value; } $content = str_replace($value, $replace, $content); } } } //如果图片没有src属性则过滤掉此img $img_preg = "/]*?src[^<>]*?>).*?>/i"; preg_match_all($img_preg,$content,$match); if (isset($match[0]) && count($match[0])) { foreach ($match[0] as $item) { $content=str_replace( $item,'',$content); } } return $content; }

你可能感兴趣的:(PHP)