Attempt at putting greedy htmlspecialchars on a diet
| From: | Gerard Samuel | Date: | Wed, 01 Oct 2003 05:12:16 +0000 |
| Subject: | Attempt at putting greedy htmlspecialchars on a diet | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-164482@lists.php.net to get a copy of this message | ||
Got a problem with htmlspecialchars being too greedy, where
for example, it converts
&foo;
to
&foo;
Yes it displays correctly in the browser for some content, but not all. (an example is posted below)
So I came up with this example code, but not sure if there is an easier/better way to get the correct end result.
If there is a better way, feel free to let me know.
Thanks
Note: I dont read/speak chinese, so if its offensive please forgive me.
------
<?php
$foo = '中文 & http://www.foo.com/index.php?foo=1&bar=2';
// Original string with chinese output but not XHTML friendly
echo "<p>$foo</p>\n\n";
$foo = htmlspecialchars($foo);
// After htmlspecialchars, XHTML is friendly but has broken chinese output
echo "<p>$foo</p>\n\n";
$foo = preg_replace('/&(#?[a-z0-9]+;)/', '&' . '$1', $foo);
// Both XHTML friendly and correct chinese output
echo "<p>$foo</p>";
?>