note 59886 added to function.htmlentities

From: Date: Mon, 19 Dec 2005 12:35:19 +0000
Subject: note 59886 added to function.htmlentities
Groups: php.notes 
Request: Send a blank email to php-notes+get-100407@lists.php.net to get a copy of this message
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 $_; } ?> ---- Manual Page -- http://www.php.net/manual/en/function.htmlentities.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+59886 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+59886&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+59886&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+59886&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+59886&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+59886&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+59886&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+59886&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+59886&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#100407) next »