title: Converting smart quotes and other entities to exact form
body: <p>I have been working with converting strings to PDFs. A typical problem that arises is the occasional 'smart quote' or other utf-8 character which becomes one or another ISO character such as â€“, â€™, â€œ , â€, etc. The function defined below solves said problem by encoding them to html entities, however, of course a PDF is not html. When inputting a string with <code>â€™</code> in place for an apostrophe <code>’</code>, the function converts it to <code>&amp;#8217;</code>. That's great if we were dealing with HTML, but as a PDF, it treats it as a string and therefore it's exact form is never converted. Therefore, how does one covert the htmlentity to the characters <em>exact</em> form?</p>
  
  <pre><code>function htmlallentities($str){
      $res = '';
      $strlen = strlen($str);
      for($i=0; $i&lt;$strlen; $i++){
          $byte = ord($str[$i]);
          if($byte &lt; 128) { // 1-byte char
              $res .= $str[$i];
          } elseif($byte &lt; 192) { // invalid utf8
          } elseif($byte &lt; 224) { // 2-byte char
              $res .= '&amp;#'.((63&amp;$byte)*64 + (63&amp;ord($str[++$i]))).';';
          } elseif($byte &lt; 240) { // 3-byte char
              $res .= '&amp;#'.((15&amp;$byte)*4096 + (63&amp;ord($str[++$i]))*64 + (63&amp;ord($str[++$i]))).';';
          } elseif($byte &lt; 248) { // 4-byte char
              $res .= '&amp;#'.((15&amp;$byte)*262144 + (63&amp;ord($str[++$i]))*4096 + (63&amp;ord($str[++$i]))*64 + (63&amp;ord($str[++$i]))).';';
          }
      }
      return $res;
  }
  </code></pre>
  
  <p>(With thanks to @Floern, <a href="https://stackoverflow.com/a/4583465/810821">https://stackoverflow.com/a/4583465/810821</a>)</p>
  
  <p>If I have used incorrect terminology, my apologies. </p>
  
  <p>Thank you in advance.</p>