在textarea的nl2br()用BBCode和HTML代码 [英] nl2br() in textarea with BBCode and HTML code

查看:120
本文介绍了在textarea的nl2br()用BBCode和HTML代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个textarea,用户可以同时使用BBCode和HTML代码,以便在数据库中插入新闻。当我想在网站上显示这个消息时,PHP脚本将BBCode转换为HTML实体,并将HTML标准中的新闻内容(从数据库获取)转换为HTML标记。问题是当我想用 nl2br()函数将换行符转换为< br /> 标签时,因为 < br /> 也会添加到HTML代码之后,例如:

I have a textarea where an user can use both BBCode and HTML code in order to insert news in database. When I want to show this news in site, PHP script convert BBCode to HTML entities and convert news content (get from database) in HTML standard preserving HTML tags. The problem is when I want to convert newline to <br /> tag with nl2br() function, because <br /> is added after HTML tags too, for example:

<li>Some text</li><br />

<table><br />
<tr><br />
etc.

有没有办法避免这个恼人的问题?

Is there a way to avoid this annoying problem?

推荐答案

我正在考虑一个正则表达式。这应该只适用于文本没有被< p>< / p> 分开的情况(这在我看来会更好一些)。

I am thinking about a regex. This should only work if texts are not separated by <p></p> (which in my opinion would be a little better).

$formattedText = preg_replace("/(<[a-zA-Z0-9=\"\/\ ]+>)<br\ \/>/", "$1", nl2br($text));

如前所述,另一种选择是在特定标签内查找文本,并将< p> 标签包裹起来。

As mentioned, the other option would be to look for text inside specific tags, and wrap around <p> tags.

这篇关于在textarea的nl2br()用BBCode和HTML代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆