Reputation: 21
In htmlentities, how do I selectively encode the symbols so that it doesn't encode the <
and >
of tags but does encode &
?
Upvotes: 2
Views: 773
Reputation: 4502
Just use:
<?php
$string = str_replace('&', '&', $string);
Refer this for details about str_replace from Official documentation.
Upvotes: 3
Reputation: 11478
Try something like this:
$string = htmlentities($string);
$string = str_replace(array('<','>'), array('<', '>'), $string);
At official documentation, htmlentities and str_replace
Upvotes: 1
Reputation: 536369
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('>', '>', str_replace('<', '<', 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('&', '&', $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.
Upvotes: 2