微信小程序显示富文本编辑器里的内容

微信小程序默认不支持html代码,所以直接读取会报错。

首先将富文本转换成文字和图片单独分开。

function html2Wxml($content)
{
    $_arr = preg_split('/(<img.*?>)/i', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    $_r = array();
    foreach($_arr as $_txt) {
        if(substr($_txt, 0, 4) == '<img') {
            $_matchs = array();
            preg_match('/<img.*?src="(.*?)"/i', $_txt, $_matchs);
            $_txt = $_matchs[1];
            if(preg_match('/^\//', $_txt)) $_txt = $cfg_basehost.$_txt;
            $_r[]= array('type'=>'img', 'data'=>$_txt);
        }else {
            $_txt = preg_replace('/&.*?;/', ' ', $_txt);
            $_txt = preg_replace('/\s+/', ' ', $_txt);
            $_txt = preg_replace(array('/<br.*?>/i', '/<p.*?>/i', '/<li.*?>/i', '/<div.*?>/i', '/<tr.*?>/i', '/<th.*?>/i'),
                "\n", $_txt);
            $_txt = preg_replace('/<.*?>/', '', $_txt);
            $_r[]= array('type'=>'txt', 'data'=>$_txt);
        }
    }
    return $_r;
}

在微信模板页面wxml文件里,使用如下模板:

<template name="img">
<view style="display: flex;justify-content:center">
<image class="content-img" mode="aspectFit" src="{{item.data}}"></image>
</view>
</template>
<template name="txt">
<view>
<text>{{item.data}}</text>
</view>
</template>
<view class="content">
<block wx:for="{{article.body}}">
<template is="{{item.type}}" data="{{item}}"/>
</block>
</view>

参考:http://www.cnblogs.com/zouzhe0/p/6269506.html

发表评论

邮箱地址不会被公开。 必填项已用*标注