According to a function here, http://www.unicodetools.com/unicode/convert-to-html.php, the function is used to convert string to HTML encoded text.
The JavaScript is:
function a(b) {
var c= '';
for(i=0; i<b.length; i++) {
if(b.charCodeAt(i)>127) {
c += '&#' + b.charCodeAt(i) + ';';
} else {
c += b.charAt(i);
}
}
document.forms.conversionForm.outputText.value = c;
}
And my try is:
function str_to_html_entity($str) {
$output = NULL;
for($i = 0; $i < strlen($str); $i++) {
if(ord($str) > 127) {
$output .= '&#' + ord($str) + ';';
} else {
$output .= substr($str, $i);
}
}
return $output;
}
echo str_to_html_entity("Thére Àre sôme spëcial charâcters ïn thìs têxt");
My PHP function run correctly, but the result is not what I expected:
my result:
Thére Àre sôme spëcial charâcters ïn thìs têxthére Àre sôme spëcial charâcters ïn thìs têxtére Àre sôme spëcial charâcters ïn thìs têxt�re Àre sôme spëcial charâcters ïn thìs têxtre Àre sôme spëcial charâcters ïn thìs têxte Àre sôme spëcial charâcters ïn thìs têxt Àre sôme spëcial charâcters ïn thìs têxtÀre sôme spëcial charâcters ïn thìs têxt�re sôme spëcial charâcters ïn thìs têxtre sôme spëcial charâcters ïn thìs têxte sôme spëcial charâcters ïn thìs têxt sôme spëcial charâcters ïn thìs têxtsôme spëcial charâcters ïn thìs têxtôme spëcial charâcters ïn thìs têxt�me spëcial charâcters ïn thìs têxtme spëcial charâcters ïn thìs têxte spëcial charâcters ïn thìs têxt spëcial charâcters ïn thìs têxtspëcial charâcters ïn thìs têxtpëcial charâcters ïn thìs têxtëcial charâcters ïn thìs têxt�cial charâcters ïn thìs têxtcial charâcters ïn thìs têxtial charâcters ïn thìs têxtal charâcters ïn thìs têxtl charâcters ïn thìs têxt charâcters ïn thìs têxtcharâcters ïn thìs têxtharâcters ïn thìs têxtarâcters ïn thìs têxtrâcters ïn thìs têxtâcters ïn thìs têxt�cters ïn thìs têxtcters ïn thìs têxtters ïn thìs têxters ïn thìs têxtrs ïn thìs têxts ïn thìs têxt ïn thìs têxtïn thìs têxt�n thìs têxtn thìs têxt thìs têxtthìs têxthìs têxtìs têxt�s têxts têxt têxttêxtêxt�xtxtt
expected result:
Thére Àre sôme spëcial charâcters ïn thìs têxt
Could someone please advise what wrong with my PHP function?
Thanks
UPDATE
function str_to_html_entity($str) {
$result = null;
for ($i = 0, $length = mb_strlen($str, 'UTF-8'); $i < $length; $i++) {
$character = mb_substr($str, $i, 1, 'UTF-8');
if (strlen($character) > 1) { // the character consists of more than 1 byte
$character = htmlentities($character, ENT_COMPAT, 'UTF-8');
}
$result .= $character;
}
return $result;
}
echo str_to_html_entity("Thére Àre"); // Thére Àre
echo str_to_html_entity("中"); // 中