Gist Shortcode Embed

By  on  

Blog comments and forum posts are traditionally the worst place to post code, but unfortunately are the frequent hosts of code for developers like us.  Many developers choose to post links to more dev-friendly environments like GitHub instead, but there's a certain disconnect that comes with posting an external resource for something that would be much more useful in an internal capacity.  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!


There are two formats to detect:  shortcode [gist #####] format and simple gist link format:

	Embed format: <script src=""></script>

function embedGists($string) {
	$regex1 = '/https:\/\/\/(\d+)/';
	$regex2 = '/\[gist (\d+)\]/';
	$replace = '<script src="${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:';
echo embedGists($string);

/* Provides:  

	lah blah<br /><script src=""></script><br />And another: <script src=""></script>


Since GitHub is so popular and their gist embed is so useful, using their embed functionality is a logic choice.  Better yet is that detection and output is easy to implement.  Consider GitHub gist embedding as a viable option for your tech-oriented website -- your users will be grateful!

Track.js Error Reporting

Upcoming Events

Recent Features

Incredible Demos

  • CSS Circles

    A while back I shared a clever technique for creating triangles with only CSS. Over the past year, I've found CSS triangles incredibly effective, especially when looking to create tooltips or design elements with a likewise pointer pattern. There's another common shape...

  • MooTools PulseFade Plugin

    I was recently driven to create a MooTools plugin that would take an element and fade it to a min from a max for a given number of times. Here's the result of my Moo-foolery. The MooTools JavaScript Options of the class include: min: (defaults to .5) the...


  1. You should also take a look at Async loading gists:

  2. [gist Is this working here?]

    • This feature will come with the next push of the site on February 1st. :)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!