Convert Smart Quotes with PHP
A 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:
<?php
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:
<?php
$replace = array('‘',
'’',
'“',
'”',
'—');
?>
These entities render properly in most browsers I've tried, including lynx. Here's some example HTML:
‘single quotes’
“double quotes”
em—dash
Here is how these entities render in your browser:
‘single quotes’ “double quotes” em—dash
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.





19 Comments
1.
Krijn Hoetmer said:
2.
Ben Ramsey said:
3.
John Wilkins said:
4.
András Bártházi said:
5.
Nev said:
6.
Chris Shiflett said:
7.
Douglas Clifton said:
8.
Douglas Clifton said:
9.
Don Laur said:
10.
marcus said:
11.
Richard Lynch said:
12.
Jonas said:
13.
Mark said:
14.
John said:
15.
Dan said:
16.
Adam Bergstein said:
17.
Bob said:
18.
Nathan said:
19.
Zac said: