Easy ASCII to HTML conversion subroutine in PHP.

I know there has to be a half-million ways to do this, and PHP offers at least, oh, three of them, natively.

Suppose, though, that htmlentities(), htmlspecialchars(), and the like don’t quite do what you want. Let us assume that you want to convert an entire string into it’s HTML equivalent, to, oh, say, attempt to mask off your email address from address harvesters.

As most email addresses have valid lower-ascii characters, they’re fine for legit HTML use, and won’t be translated. Enter ‘htmlify’, a simple little function.

function htmlify($myText) { // Pre-init our type. $transArray = array(); // Fill it in with the proper numerics, char ~= &#num-of-char for ($i=0; $i<255; $i++) { $transArray[chr($i)] = “&#” . $i . ”;”; } // Spew it back as HTML. return strtr($myText, $transArray); }

It’s use is quite simple – just call it with the string you want to modify, and it’ll do the rest. Ex:

function main(){ $myEmail = “spamme@silly.org” echo htmlify($myemail);
}
?>

I’ve tested a few alternatives, just for the sake of completeness, and optimization. This one is the fastest by far. Someone else’s solution, which does a foreach on the string (blawgh), then converts each character as it sees it, takes about 4 times that than the above ‘lookup table’ sort.

Woohoo. I roxxor, or something. ;)