note 59886 deleted from function.htmlentities by bjori

From: Date: Fri, 21 Apr 2006 10:17:51 +0000
Subject: note 59886 deleted from function.htmlentities by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-108910@lists.php.net to get a copy of this message
Note Submitter: nospam at donadio dot com dot br ---- Sometimes you need to escape stuff for JavaScript, not HTML. I just modified the function posted by webmaster at swirldrop dot com. The difference is that while htmlencoded strings are something like "&#20;", JavaScript requires something like "\x20". The function below cuts it; <?php function js_escape_string($str){ return preg_replace('/[^!-%\x27-;=?-~ ]/e', '"\\x".ord("$0")', $str); } ?> Also, note some problems with people copying and pasting from MS Word and other word processors. They usually come with "strange" characters, like "curly" quotes (a.k.a. "typographer's quotes", "educated quotes" and "smart quotes"). These won't be encoded by the function above, nor will they be escaped by addslashes, for example. In my case, I wanted to straighten all the quotes. Check the function below, extracted from SmartyPants <http://daringfireball.net>. It does it, and comes wih some other goodies): <?php function StupefyEntities($_) { # # Parameter: String. # Returns: The string, with each SmartyPants HTML entity translated to # its ASCII counterpart. # # Example input: &#8220;Hello &#8212; world.&#8221; # Example output: "Hello -- world." # # en-dash em-dash $_ = str_replace(array('&#8211;', '&#8212;'), array('-', '--'), $_); # single quote open close $_ = str_replace(array('&#8216;', '&#8217;'), "'", $_); # double quote open close $_ = str_replace(array('&#8220;', '&#8221;'), '"', $_); $_ = str_replace('&#8230;', '...', $_); # ellipsis return $_; } ?>

« previous php.notes (#108910) next »