开发者社区> 问答> 正文

Kindeditor 修改内容时如何不让 < 被自动转义:报错

本人新手,用PHP&MySQL写了个文章发布系统,富文本编辑器使用的是Kindeditor。

症状说明:

我想通过编辑器发些代码,添加文章时可以正常发代码,包括 < 也被正常转义为 < ,保存到数据库中也是 <。

但如果修改文章,从数据库中读取到的 < 会被 KindEditor 自动转义为 < ,导致内容无法正确显示。

以下是 Kindeditor 的调用代码

			KE.show({
				id : 'content',
				urlType: 'absolute',
				imageUploadJson : '../../upload_img.php',	//相对于kindeditor\plugins\image\image.html
				fileManagerJson : '../../select_img.php',	//相对于kindeditor\plugins\file_manager\file_manager.html
				allowFileManager : true,
			});

数据是直接通过 $_POST['content'] 提交到 MySQL 中的,没有任何转义。

翻过 oschina 的帖子,也有人提出类似的问题,红署哥哥的回答是把 & 转义为 & ,于是我就使用PHP的 str_replace()函数把&转义成&。

这样 < 就变成了 &lt ,这倒是可以解决 Kindeditor 自动转义 < 的问题,但如果我打一个空格也就是   也变成了 &nbsp ,无法正常显示空格。

究竟该如何解决特殊字符转义的问题呢?

展开
收起
kun坤 2020-06-06 17:13:30 1000 0
1 条回答
写回答
取消 提交回答
  • oschina 的转换方法如下,确保无误(  转成 &nbsp 还是空格的)

    /** * 格式化HTML文本 * @param content * @return */ public static String rhtml(String content) { if(StringUtils.isBlank(content)) return content; String html = content; html = StringUtils.replace(html, "&", "&"); html = StringUtils.replace(html, "<", "<"); html = StringUtils.replace(html, ">", ">"); return html; }
    ######

    把 & 转换成 & 再保存入数据库,在前台输出时需要重新 str_replace('&', '&', $content);

    但在 kindeditor 编辑器中不需要,好像它会自己把 & 转换成 & ,我修改文章时看 kindeditor 中的源码 & 都变成了&

    别的编辑器也是这样的吗? kindeditor 为什么这样转换呢,感觉麻烦了许多,是不是有什么好处啊?

     

    ######

    我是这么处理的:

     $content = str_replace('  ','@@@#@@',$content);

    $content = str_replace(' ',' ',$content);

    $content = str_replace('@@@#@@','  ',$content);

    因为KE将连续的空格自动解析为: 空格+  但是单个空格又自动转换为  ..

    所以这个看起来比较复杂!

    ######

    试试 @红薯 就这个连续空格的问题是否有处理?

    红 薯

    红   薯 (3个空格)

    红    薯(4个空格)

    红     薯(5个空格)

    ###### 红     薯###### 红            薯######

    已经用上了,感谢!

    function kindhtml($html,$jc='j'){
     if($jc=='j'){
      $html = str_replace(' ', '&nbsp;', $html);
      $html = str_replace('>', '&gt;', $html);
      $html = str_replace('<', '&lt;', $html);
     }
     //仅用在非kindeditor文本编辑器页面使用,因为kindeditor文本编辑器会自动执行下面这类转换
     if($jc=='c'){
      $html = str_replace(' ', '&nbsp;', $html);
      $html = str_replace('>', '&gt;', $html);
      $html = str_replace('<', '&lt;', $html);
     }
    }



    ######

    求答案

    2020-06-06 17:13:35
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载