title: Parse UTF-8 string char-by-char in PHP
body: <p>I'm sorry if I'm asking the obvious, but I can't seem to find a working solution for a simple task. On the input I have a string, provided by a user, encoded with UTF-8 encoding. I need to sanitize it by removing all characters less than <code>0x20</code> (or space), except <code>0x7</code> (or tab.)</p>
  
  <p>The following works for ANSI strings, but not for UTF-8:</p>
  
  <pre><code>$newName = "";
  $ln = strlen($name);
  for($i = 0; $i &lt; $ln; $i++)
  {
      $ch = substr($name, $i, 1);
      $och = ord($ch);
      if($och &gt;= 0x20 ||
          $och == 0x9)
      {
          $newName .= $ch;
      }
  }
  </code></pre>
  
  <p>It totally missed UTF-8 encoded characters and treats them as bytes. I keep finding posts where people suggest using <code>mb_</code> functions, but that still doesn't help me. (For instance, I tried calling <code>mb_strlen($name, "utf-8");</code> instead of <code>strlen</code>, but it still returns the length of string in <code>BYTEs</code> instead of characters.)</p>
  
  <p>Any idea how to do this in PHP?</p>
  
  <p>PS. Sorry, my PHP is somewhat rusty.</p>