开放的编程资料库

当前位置:我爱分享网 > PHP教程 > 正文

要点简码嵌入

博客评论和论坛帖子传统上是最糟糕的发布代码的地方,但不幸的是,对于像我们这样的开发人员来说,它们经常是代码的宿主。许多开发人员选择发布指向对开发人员更友好的环境(如 GitHub)的链接,但是为某些在内部容量中更有用的内容发布外部资源会带来一定的脱节。使用一些服务器端魔法(在本例中为 PHP)和正则表达式,我们可以利用 GitHub 的 Gist API 根据需要在评论和论坛帖子中显示外部代码!

PHP

有两种格式可供检测:简码 [gist #####] 格式和简单的 gist 链接格式:

/*
	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>

*/

由于 GitHub 如此受欢迎并且他们的 gist 嵌入非常有用,因此使用他们的嵌入功能是一个合乎逻辑的选择。更好的是检测和输出很容易实现。考虑将 GitHub gist 嵌入作为面向技术的网站的可行选择——您的用户将不胜感激!

未经允许不得转载:我爱分享网 » 要点简码嵌入

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏