Convert Smart Quotes with PHP
31 Oct 2005A question that seems to come up pretty frequently on various PHP mailing lists is how to convert "smart quotes" to real quotes. Dan Convissor provided a simple example that performs such a conversion a year or two ago on the NYPHP mailing list. I've modified it slightly to fit my own style preferences:
function convert_smart_quotes($string)
{
$search = array(chr(145),
chr(146),
chr(147),
chr(148),
chr(151));
$replace = array("'",
"'",
'"',
'"',
'-');
return str_replace($search, $replace, $string);
}
(This function also converts an emdash into a hyphen.)
If you want "smart quotes" to actually appear in a browser, you can use the following $replace array to convert each of these characters into HTML entities:
$replace = array('‘',
'’',
'“',
'”',
'—');
These entities render properly in most browsers I've tried, including lynx. Here's some example HTML:
“double quotes”
Here is how these entities render in your browser:
“double quotes”
The htmlentities() man page has other useful examples in the user notes at the bottom, some of which convert a wide variety of characters into valid HTML entities.