note 59886 deleted from function.htmlentities by bjori
| From: | bjori@php.net | 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
"", 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: “Hello — world.”
# Example output: "Hello -- world."
#
# en-dash em-dash
$_ = str_replace(array('–', '—'),
array('-', '--'), $_);
# single quote open close
$_ = str_replace(array('‘', '’'), "'", $_);
# double quote open close
$_ = str_replace(array('“', '”'), '"', $_);
$_ = str_replace('…', '...', $_); # ellipsis
return $_;
}
?>