2

In htmlentities, how do I selectively encode the symbols so that it doesn't encode the < and > of tags but does encode &?

3
  • 2
    Are you talking about ".:;,!?"? If so, why do you want to encode them? Or are you talking about quotation marks? Commented Nov 5, 2010 at 20:57
  • 1
    1. never use htmlentities. 2. never encode anything beside < and >, & and quotes. Commented Nov 5, 2010 at 20:59
  • 2
    The right solution to this problem is likely to be "Forget about encoding entities and just make sure you declare the character encoding you are using": w3.org/International/O-charset Commented Nov 5, 2010 at 21:00

3 Answers 3

3

Just use:

<?php
$string = str_replace('&', '&amp;', $string);

Refer this for details about str_replace from Official documentation.

Sign up to request clarification or add additional context in comments.

Comments

2

You don't get a ‘partially-encode’ option; if there are particular characters you want to be escaped or not escaped you will have to do it manually. For example to do what you say you want:

str_replace('&gt;', '>', str_replace('&lt;', '<', htmlentities($s)))

What is it you're trying to do, though? The above seems very unlikely to be useful. " characters in markup will still be escaped, mangling attribute values.

htmlentities is also in general questionable, because unless you specifically feed it the right charset argument it will mangle any non-ASCII characters in the string into wrong HTML entity references. It is usually better to use htmlspecialchars(), which only affects the few characters that really are special and need escaping in HTML.

If all you want to do is escape the & character you can do that with a simple str_replace('&', '&amp;', $s) but again, that would still replace ampersands that are part of a valid entity or character reference. Are you sure you want to do that? Are you just trying to fix up incorrectly-used unescaped ampersands? If so you could try a regex to select any use of a & that isn't a valid entity/character reference.

Comments

1

Try something like this:

$string = htmlentities($string);
$string = str_replace(array('&lt;','&gt;'), array('<', '>'), $string);

At official documentation, htmlentities and str_replace

3 Comments

err... in the second example, you forgot one parameter
@Col It looks like the original post wanted to use htmlentities to encode everything except for < and >
It looks like that the original poster have no idea what is he doing. Like many other posters. Do YOU see any sense in your answer? Why race to answer a poor question? Why to answer literally? We are not robots. We are humans. Who can think before act. At least supposed to.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.