将纯文本格式化为HTML标记

时间:2013-05-31 00:20:42

标签: php html cakephp format

我正在使用cakephp作为我的网络应用程序。我有一个数据库表,我存储了一些以纯文本保存的文字。我该怎么做才能得到它自己格式化的文本?html标记?

例如,我在数据库上有一个文本,如:

blablablabalbalblablablablablablablablabalbalbla.
otherotherotherotherotherother.
helloworldhelloworldhelloworldhelloworld.

但是当我得到它时就会显示出来:

blablablabalbalblablablablablablablablabalbalbla.otherotherotherotherotherother.helloworldhelloworldhelloworldhelloworld.

但是我希望它像这样进入html:

<p>blablablabalbalblablablablablablablablabalbalbla.</p>
<p>otherotherotherotherotherother.</p>
<p>helloworldhelloworldhelloworldhelloworld.</p>

无论如何都要这样做?

3 个答案:

答案 0 :(得分:5)

如果您只想保留线刹,可以将文字换成&lt; pre&gt;标签

<pre>
blablablabalbalblablablablablablablablabalbalbla.
otherotherotherotherotherother.
helloworldhelloworldhelloworldhelloworld.
</pre>

否则在换行符上使用php替换str_replace等函数。 例如:

$in = '
blablablabalbalblablablablablablablablabalbalbla.
otherotherotherotherotherother.
helloworldhelloworldhelloworldhelloworld.';

$out = '<p>'
$out .= str_replace("\n\r" , '</p><p>', $in);
$out .= '</p>';

echo $out;

答案 1 :(得分:2)

如果您正在 - 或将要 - 使用Cake2.4,它有一种新方法来相应地格式化您的代码:

echo $this->Text->autoParagraph($text);

https://github.com/cakephp/cakephp/blob/8cb84e7aa71b09d1b91591513375b6e2ba4f31af/src/View/Helper/TextHelper.php#L296

在此之前,您可以将此方法复制到您自己的自定义帮助程序中。

请注意,您的代码不会包含在<p>中,而是包含在<br>代码中! 只有第二个换行符(在最后一行之前),您将获得另一个p标记:

blablablabalbalblablablablablablablablabalbalbla.
otherotherotherotherotherother.

helloworldhelloworldhelloworldhelloworld.

会变成

<p>blablablabalbalblablablablablablablablabalbalbla.<br />
otherotherotherotherotherother.</p>
<p>helloworldhelloworldhelloworldhelloworld.</p>

这就是标准。所以你应该坚持下去。

答案 2 :(得分:1)

您将要使用PHP的字符串函数。您可能希望在从数据库中提取的文本中找到模式或重复出现以更改字符串。在您的示例中,期间可能是一个很好的起点。也许更具体地看一下strpos()函数php和str_replace()函数以及它们是如何工作的。

我建议您尝试了解PHP字符串函数,然后尝试使用它们来解决您的问题。如果您在发布所做的事情和遇到的麻烦时遇到问题,那么人们会更容易为您提供额外的帮助。

相关问题