Convert Smart Quotes with PHP

31 Oct 2005

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:

  1.  
  2. function convert_smart_quotes($string)
  3. {
  4.     $search = array(chr(145),
  5.                     chr(146),
  6.                     chr(147),
  7.                     chr(148),
  8.                     chr(151));
  9.  
  10.     $replace = array("'",
  11.                      "'",
  12.                      '"',
  13.                      '"',
  14.                      '-');
  15.  
  16.     return str_replace($search, $replace, $string);
  17. }
  18.  

(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:

  1.  
  2. $replace = array('‘',
  3.                  '’',
  4.                  '“',
  5.                  '”',
  6.                  '—');
  7.  

These entities render properly in most browsers I've tried, including lynx. Here's some example HTML:

  1. “double quotes”

Here is how these entities render in your browser:

  1. “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.