eriurghikgbriehn
eriurghikgbriehn

Reputation: 21

PHP htmlentities

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

Answers (3)

Pascal Qyy
Pascal Qyy

Reputation: 4502

Just use:

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

Refer this for details about str_replace from Official documentation.

Upvotes: 3

Parris Varney
Parris Varney

Reputation: 11478

Try something like this:

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

At official documentation, htmlentities and str_replace

Upvotes: 1

bobince
bobince

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('&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.

Upvotes: 2

Related Questions