title: Reverse letters in each word of a string without using native splitting or reversing functions
body: <p>This task has already been asked/answered, but I recently had a job interview that imposed some additional challenges to demonstrate my ability to manipulate strings.</p>
  <p>Problem: How to reverse words in a string? You can use <code>strpos()</code>, <code>strlen()</code> and <code>substr()</code>, but not other very useful functions such as <code>explode()</code>, <code>strrev()</code>, etc.</p>
  <p>Example:</p>
  <pre><code>$string = &quot;I am a boy&quot;
  </code></pre>
  <p>Answer:</p>
  <pre><code>I ma a yob
  </code></pre>
  <p>Below is my working coding attempt that took me 2 days [sigh], but there must be a more elegant and concise solution.</p>
  <p>Intention:</p>
  <pre><code>1. get number of words
  2. based on word count, grab each word and store into array
  3. loop through array and output each word in reverse order
  </code></pre>
  <p>Code:</p>
  <pre><code>$str = &quot;I am a boy&quot;;
  
  echo reverse_word($str) . &quot;\n&quot;;
  
  function reverse_word($input) {
      //first find how many words in the string based on whitespace
      $num_ws = 0;
      $p = 0;
      while(strpos($input, &quot; &quot;, $p) !== false) {
          $num_ws ++;
          $p = strpos($input, ' ', $p) + 1;
      }
      
      echo &quot;num ws is $num_ws\n&quot;;
      
      //now start grabbing word and store into array
      $p = 0;
      for($i=0; $i&lt;$num_ws + 1; $i++) {
          $ws_index = strpos($input, &quot; &quot;, $p);
          //if no more ws, grab the rest
          if($ws_index === false) {
              $word = substr($input, $p);
          }
          else {
              $length = $ws_index - $p;
              $word = substr($input, $p, $length);
          }
          $result[] = $word;
          $p = $ws_index + 1; //move onto first char of next word
      }
      
      print_r($result);
      //append reversed words
      $str = '';
      for($i=0; $i&lt;count($result); $i++) {
          $str .= reverse($result[$i]) . &quot; &quot;;
      }
      return $str;
  }
  
  function reverse($str) {
      $a = 0;
      $b = strlen($str)-1;
      while($a &lt; $b) {
          swap($str, $a, $b);
          $a ++;
          $b --;
      }
      return $str;
  }
  
  function swap(&amp;$str, $i1, $i2) {
      $tmp = $str[$i1];
      $str[$i1] = $str[$i2];
      $str[$i2] = $tmp;
  }
  </code></pre>