微信小程序图文混排不支持的解决方法

微信 小程序 2140      收藏
微信小程序不支持动态生成页面,所以当我们将数据库的文章内容传到小程序页面的时候,传递的内容会原样显示,不进行解析。本文讲述如何解决微信小程序的图文混排问题。

自学php博客

微信小程序不支持动态生成页面,所以当我们将数据库的文章内容传到小程序页面的时候,传递的内容会原样显示,不进行解析,而是把html代码直接显示出来。本文讲述如何解决微信小程序的图文混排问题。

解决的思路是:

在服务端写接口的时候,从数据库中读取文章内容,将获取到的文章内容用正则表达式进行拆分,拆分成文章文字数组和图片数组。

然后将这两个数组返回给小程序。

小程序通过接口获取到文章数组和图片数组之后,分别进行遍历。

将内容数组遍历,并渲染到view标签中,同时根据数组的k值获取到图片对应的图片的路径,并将此地址渲染到image标签中。


服务端代码:

将ueditor上传的content内容中的图片信息提取出来:

public function _filtercontent($content){

  $content = preg_replace('/<\/?(html|head|meta|link|base|body|title|style|script|form|iframe|frame|frameset|p)[^><]*>/i','',$content);

   $pattern ='<img.*?src="(.*?)">';

   preg_match_all($pattern,$content,$matches);

   return $matches[1];

}

此方法返回的是content中的所有图片的url组成的数组。

将ueditor上传的content内容中的文字信息提取出来:

public function _setcontenttoarray($content){

   $content = preg_replace('/<\/?(img)[^><]*>/i','#',$content);

   $res = preg_replace('/<\/?(html|head|meta|link|base|body|title|style|script|form|iframe|frame|frameset|p|span|strong|sup)[^><]*>/i','',$content);

   $res = str_replace('&nbsp;', "\r\t ", $res);

   $res = str_replace('<br/><br/>', "\r\n", $res);

   $res = str_replace('<br/>', "\r\n", $res);

   $res = str_replace('<br>', "\r\n", $res);

   $arr = explode('#', $res);

   foreach( $arr as $k=>$v){   

     if( !$v )   

       unset( $arr[$k] );   

     }  

return $arr;

}

此方法返回的是content中的文字切割成的数组

用上面的两个方法处理之后,文章内容已经被拆分成了两个部分,一个是图片数组,一个是文字数组。

然后是小程序端的处理:

<view class="and_image">

<block wx:for="{{infoData.article_content}}">

<text>{{item}}</text>

<image src="{{infoData['img_arr'][index]}}" mode="widthFix"></image>

</block>

</view>