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.

1 Answer 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.

7
  • Does htmlspecialchars escape ampersands too?
    – Tim
    Apr 23, 2012 at 17:15
  • Yes, it does escape ampersands
    – John Conde
    Apr 23, 2012 at 17:16
  • Thank you for your answer. But, it also replaces signle and double quotes. I don't think they are bad symbols to display in the <span> area (that's not a text area, where " will finish the string). The more symbols I replace, the more work I have to do to analyze the string user typed. Do I really need htmlspecialchars for the task I've described? For textarea " should be replaced. For the span - why? Apr 23, 2012 at 17:18
  • 1
    In those cases switch ENT_HTML5 with ENT_NOQUOTES
    – John Conde
    Apr 23, 2012 at 17:22
  • John, thank you. In this case only &, < and > are replaced. Am I right? So, htmlspecialchars($string, ENT_NOQUOTES, "UTF-8") is actually the same for UTF-8 (everything is UTF-8) as 3 replacements of & with &amp ; < with &lt ; and > with &gt ; , but performance, and nothing else. Am I right? Apr 23, 2012 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.