Typecho 实现短代码功能。

前几天,准备对博客首页大改。在寻找灵感的途中。发现有的博客实现了一些好玩的功能。

这个短代码就是其中之一。

毕竟markdown里没有太明显的提示或警告。

稍微研究了一下。


演示

短代码标记

info:一般提示

warning:警告提示

Error:危险提示

info:多行内容测试:
生活如酒,或芳香,或浓烈,因为诚实,它变得醇厚;生活如歌,或高昂,或低沉,因为守信,它变得悦耳; 生活如画,或明丽,或素雅,因为诚信,它变得美丽。


原理

很简单的一个原理,用正则匹配短代码标签,把他替换成样式就OK了。


方法

在主题的 functions.php 的文件里,新建个函数。

 1// 短代码测试
 2	function getContentTest($content) {
 3	    $pattern = '/\[(info)\](.*?)\[\s*\/\1\s*\]/';
 4		$replacement = '<div class="hint hint-info"><span class="glyphicon glyphicon-info-sign hint-info-icon" aria-hidden="true"></span>$2</div>';	
 5		$content = preg_replace($pattern, $replacement, $content);
 6
 7		$pattern = '/\[(warning)\](.*?)\[\s*\/\1\s*\]/';
 8		$replacement = '<div class="hint hint-warning"><span class="glyphicon glyphicon-question-sign hint-warning-icon" aria-hidden="true"></span>$2</div>';	
 9		$content = preg_replace($pattern, $replacement, $content);
10
11		$pattern = '/\[(danger)\](.*?)\[\s*\/\1\s*\]/';
12		$replacement = '<div class="hint hint-danger"><span class="glyphicon glyphicon-exclamation-sign hint-danger-icon" aria-hidden="true"></span>$2</div>';	
13		$content = preg_replace($pattern, $replacement, $content);
14	    
15	    return $content;
16	}

短代码

然后把主题里输出文章内容的函数(共三处处:index.php 、page.php 和 articles.php)

1<?php $this->content(); ?>

换成你刚刚添加的

1<?php echo getContentTest($this->content); ?

articles.php

Error:注意:如果导致首页文章无法正常使用``标记截断,请移步**此处**


文章摘要去除短代码标记

原理:对excerpt函数输出的内容再次正则匹配,来在摘要中剔除 短代码标记

在输出的摘要中剔除短代码标记

 1// 摘要短代码测试
 2function getExcerptTest($excerpt,$num,$str) {
 3    $pattern = '/\[(info)\](.*?)\[\s*\/\1\s*\]/';
 4    $replacement = ' $2 ';  
 5    $excerpt = preg_replace($pattern, $replacement, $excerpt);
 6
 7    $pattern = '/\[(warning)\](.*?)\[\s*\/\1\s*\]/';
 8    $replacement = ' $2 ';  
 9    $excerpt = preg_replace($pattern, $replacement, $excerpt);
10
11    $pattern = '/\[(danger)\](.*?)\[\s*\/\1\s*\]/';
12    $replacement = ' $2 ';  
13    $excerpt = preg_replace($pattern, $replacement, $excerpt);
14
15    //使用mb_substr防止中文截取成乱码,需要开启extension=php_mbstring.dll扩展,一般都开了
16    return mb_substr($excerpt,0,$num,"UTF-8").$str;
17}

functions.php

使用下面的代码替换原有摘要输出(150是截断字数, ’ ……’ 是需要显示的提示)

1<?php echo getExcerptTest($this->text,150,' ......'); ?>

替换原有摘要输出