0

A user types any text in the textarea on html page. The string is sent to the server using AJAX and returned back to <span id="userstring"></span>. Whatever was typed in the textarea, it is displayed in the span. Everything works fine, but... When a user enters tags with a text, for example <b>hello</b>, it displays the bold word hello instead of <b>hello</b>.

So, the goal is to make THE MINIMUM CHANGES of the typed string, so it is displayed in span EXACTLY the same way as it was typed.

I decided the problem are < and > symbols, so my plan is replace them with &lt; and &gt;. In the span area will looks the same way as it was typed. Also, I should care of & symbol so when user types '&gt;' it looks &gt;, that's why & should be replaced with &amp;. Is there anything else I should take care of? I don't insert a string into the mysql db, so I don't take any precautions of ' etc. But, I work with that string so I want to keep minimum changes of the string. Replacing &, < and > only are OK. Did I forget something?

Thank you.

4

1 回答 1

5

Use htmlspecialchars()

<php
$string = '<b>bold text</b>';
echo htmlspecialchars($string, ENT_HTML5, "UTF-8"); 
?>

If you omit ENT_HTML5, it will default to ENT_HTML401 | ENT_COMPAT. In the above code, ENT_COMPAT is overridden so the quote character (") will not be escaped anymore.

于 2012-04-23T17:14:28.743 回答