微信小程序转php,微信小程序中富文本转文本的实现

这篇文章主要介绍了微信小程序 富文本转文本实例详解的相关资料,需要的朋友可以参考下

微信小程序-富文本转文本

最近小程序这么火,我也来搞搞。发现了一个恶心的问题。小程序没有组件能支持富文本内容的,改接口又不太合适,于是有了这问,没技术含量纯粹记录

首先我们看眼没有被格式的富文本显示:

*.wxml内代码。content是富文本内容

{{content}}

显示结果:

9042c28c703e2a41e87c4a21fbe2d40b.png

由以上图片看到,小程序无法解析html文件

我们需要处理html富文本内容,让其显示好看点

下面直接上代码了,主要功能就是利用js的replace 对富文本经行处理,大家可以看一下。一起优化,方便对富文本更好的处理。

convertHtmlToText: function convertHtmlToText(inputText) {

var returnText = "" + inputText;

returnText = returnText.replace(//ig, '\r\n');

returnText = returnText.replace(//ig, '\r\n');

returnText = returnText.replace(/

/ig, ' * ');

returnText = returnText.replace(//ig, '\r\n');

//-- remove BR tags and replace them with line break

returnText = returnText.replace(/
/gi, "\r\n");

//-- remove P and A tags but preserve what's inside of them

returnText=returnText.replace(/

/gi, "\r\n");

returnText=returnText.replace(/(.*?)/gi, " $2 ($1)");

//-- remove all inside SCRIPT and STYLE tags

returnText=returnText.replace(/[\w\W]{1,}(.*?)[\w\W]{1,}/gi, "");

returnText=returnText.replace(/[\w\W]{1,}(.*?)[\w\W]{1,}/gi, "");

//-- remove all else

returnText=returnText.replace(//g, "");

//-- get rid of more than 2 multiple line breaks:

returnText=returnText.replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\r\n\r\n");

//-- get rid of more than 2 spaces:

returnText = returnText.replace(/ +(?= )/g,'');

//-- get rid of html-encoded characters:

returnText=returnText.replace(/ /gi," ");

returnText=returnText.replace(/&/gi,"&");

returnText=returnText.replace(/"/gi,'"');

returnText=returnText.replace(/

returnText=returnText.replace(/>/gi,'>');

return returnText;

}

将上面代码放入任意适合的小程序js文件中, 然后在需要处理数据的js文件里,引入文件,下面给出放入app.js文件中的调用示

例:

var app = getApp()//获取app小程序实例

onLoad: function (options) {

wx.request({

url: 'http://example.com/api' + options.id+'.json',

headers: {

'Content-Type': 'application/json'

},

success: function (res) {

res.data.content = app.convertHtmlToText(res.data.content )

that.setData({

art: res.data.content

})

console.log(res.data)

}

})

然后编译刷新下,可以看到结果了:

99cad5a4be966808cfd8600a76505ab4.png

这里可以继续调整下css,使显示得更好看点。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值