Skip to main content

Using some server-side magic (PHP in this case) and regular expressions, we can utilize GitHub's Gist API to display external code within comments and forum posts as desired!

Read full post...

/*
  Embed format: <script src="https://gist.github.com/4575399.js"></script>
*/

function embedGists($string) {
  $regex1 = '/https://gist.github.com/(d+)/';
  $regex2 = '/[gist (d+)]/';
  $replace = '<script src="https://gist.github.com/${1}.js"></script>';

  // Find [gist ######] stuff
  $string = preg_replace($regex1, $replace, $string);
  $string = preg_replace($regex2, $replace, $string);

  return $string;
}

// Test string
$string = 'lah blah<br />[gist 4575399]<br />And another: https://gist.github.com/4575399';
echo embedGists($string);

/* Provides:

  lah blah<br /><script src="https://gist.github.com/4575399.js"></script><br />And another: <script src="https://gist.github.com/4575399.js"></script>

*/