将纯文本转换为HTML,但仅转换为链接


Make plain text to HTML but only links?

场景是:

  1. 用户将大量内容放在保存到数据库的文本区域中
  2. 保存的内容是使用htmlentities()"确保纯文本"

当输出到网页时,它显示为这样(链接也显示为纯文本)

Hello there, how are you today. 
This text is saved and I want to show links, 
but the links are displayed like this: <a href="text">text</a>.
(because the html surrounding the link are &lt; and &gt;)

我这样做(纯文本)是因为我不想让用户用HTML标签等把内容搞砸。

是否可以将CCD_ 2和CCD_;和>,但仅当存在链接时?我不知道如何做到这一点。

更新:一个想法可能是使用像[mylink]actual link[/mylink]这样的自定义标记。也可以。这可能是一个更好的解决方案?你有什么想法?

不使用htmlentities,而是使用strip_tags:

strip_tags——从字符串中剥离HTML和PHP标记

有一个选项允许忽略某些标记。在您的示例中:

$text="This <b>is</b> a <a href='#'>test</a>";
echo strip_tags($text,'<a>');

这将删除除锚以外的所有HTML标记。