PHP Function - Extended Entity Conversion

This function serves as an extended version of htmlentities() and htmlspecialchars(). It converts all characters from ASCII 126 to ASCII 255 into their respective HTML entity codes.

function char_entities($data) {
	for ($i = 126; $i < = 255; $i++) {
		if ($i != 160) {
			$badchars[$i]  = chr($i);
			$goodchars[$i] = "&#$i;";
		}
	}

	// Normalize quotes and em dashes (e.g. - MS Word crap)
	$goodchars[145] = '\\'';
	$goodchars[146] = '\\'';
	$goodchars[147] = '"';
	$goodchars[148] = '"';
	$goodchars[151] = '-';
	// We don't want to convert spaces!
	unset($badchars[160]);
	unset($goodchars[160]);

	return str_replace($badchars, $goodchars, $data);
}

As a side note, it seems that WordPress throws a “503 Service Temporarily Unavailable” error when submitting posts that contain the following string (possibly any use of chr()):

chr($i);

I had to escape it in order to get it to work:

chr&#40;$i&#41;

Leave a Reply