title: How to convert RGBA color codes to 8 Digit Hex in PHP?
body: <p>I'm attempting to convert some <a href="https://en.wikipedia.org/wiki/RGBA_color_model" rel="nofollow noreferrer">rgba</a> values into a format suitable for <a href="https://en.wikipedia.org/wiki/SubStation_Alpha" rel="nofollow noreferrer">SubStation Alpha subtitle files</a>. The <code>.ass</code> file format requires a colour format like <code>&amp;H12345690</code> where the hex bytes are in blue, green, red, alpha order.</p>
  <p>I am finding examples converting 8 digit hex colors into RGBA, but not the other way around. Here is a function I put together based one of the answers, but the alpha channel is always returned as zero:</p>
  <pre class="lang-php prettyprint-override"><code>function rgbtohex($string) {
      $string = str_replace(&quot;rgba&quot;,&quot;&quot;,$string);
      $string = str_replace(&quot;rgb&quot;,&quot;&quot;,$string);
      $string = str_replace(&quot;(&quot;,&quot;&quot;,$string);
      $string = str_replace(&quot;)&quot;,&quot;&quot;,$string);
      $colorexplode = explode(&quot;,&quot;,$string);    
      $hex = '&amp;H';
      
      foreach($colorexplode AS $c) {
          echo &quot;C&quot; . $c . &quot; &quot; . dechex($c) . &quot;&lt;br&gt;&lt;br&gt;&quot;;
          $hex .= dechex($c);      
      }
      return $hex;
  }
  </code></pre>
  <p>But if I test it with <code>rgba(123,223,215,.9)</code> it produces <code>&amp;H7bdfd70</code> which only has 7 characters instead of 8.</p>
  <p>Also, the alpha channel (.9) always comes out to zero, so that doesn't appear to be working correctly.</p>