Make plain text to HTML but only links?

时间:2016-04-07 10:29:03

标签: php html html-entities

The scenario is:

  1. A user puts a lot content in a textarea that is saved to database.
  2. The saved content are "ensure plain text" by using htmlentities().

And when output to a webpage it shows like this (and the link is shown as plain text as well)

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;)

I've made it like this (plain text only) because I don't want users to mess up the the content with HTML tags etc.

Is it possible to replace &gt; and &lt; into < and > but only when there is a link? I'm not sure how to achieve this.

UPDATE: A thought might be using a custom tag like [mylink]actual link[/mylink]. It would be OK as well. This might be a better solution? What are your thoughts?

1 个答案:

答案 0 :(得分:2)

Instead of using htmlentities use strip_tags:

strip_tags — Strip HTML and PHP tags from a string

There is an option that allows to ignore certain tags. In your example:

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

That will remove every HTML tag but the anchors.