title: How to check if a string can safely be converted in another character set without loss?
body: <p>Is it possible, prior to converting a string from a charset to another, to know whether this conversion will be lossless?</p>
  
  <p>If I try to convert an UTF-8 string to latin1, for example, the chars that can't be converted are replaced by <code>?</code>. Checking for <code>?</code> in the result string to find out if the conversion was lossless is obviously not a choice.</p>
  
  <p>The only solution I can see right now is to convert back to the original charset, and compare to the original string:</p>
  
  <pre class="lang-php prettyprint-override"><code>function canBeSafelyConverted($string, $fromEncoding, $toEncoding)
  {
      $encoded = mb_convert_encoding($string, $toEncoding, $fromEncoding);
      $decoded = mb_convert_encoding($encoded, $fromEncoding, $toEncoding);
  
      return $decoded == $string;
  }
  </code></pre>
  
  <p>This is just a quick&amp;dirty one though, that may come with unexpected behaviours at times, and I guess there might be a cleaner way to do this with <a href="http://php.net/manual/en/book.mbstring.php" rel="nofollow">mbstring</a>, <a href="http://php.net/manual/en/book.iconv.php" rel="nofollow">iconv</a>, or any other library.</p>