木匣子

Web/Game/Programming/Life etc.

split or explode it?

刚才在社区里有人提问如果将帖子从<!--more-->分割开,获得摘要和剩余内容。

有仁兄回答说用 split() :

$post = split("<!--more-->", $context, 2);
$summary = $post[0];
$extended = $post[1];

但是注意到PHP手册里面有这样一句话:

Tip preg_split() 函数使用了 Perl 兼容正则表达式语法,通常是比 split() 更快的替代方案。如果不需要正则表达式的威力,则使用 explode() 更快,这样就不会招致正则表达式引擎的浪费。

也就是说,如果分隔符是常量的话,使用 explode() 可以更加高效。

$post = explode("<!--more-->", $context, 2);
$summary = $post[0];
$extended = $post[1];

实际上 split() 在 PHP 5.3.0 已经被弃用:

Warning This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

有意思的是这个 warning 只出现在英文文档里,而中文文档里只是一个 Tip.

Wordpress 实现

Wordpress 允许用户正定义 more 标记:<!--more[user tag]-->,所以 Wordpress 不得不采用正则表达式。但它并没有使用 split() 或者 preg_split(),而是先用 preg_match() 找到自定义 more 标记,再用 explode() 完成分割。

if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
	list($main, $extended) = explode($matches[0], $post, 2);
	$more_text = $matches[1];
} else {
	$main = $post;
	$extended = '';
	$more_text = '';
}

Typecho 实现

Typecho 只是简单使用字符串常量 <!--more-->,所以直接使用了 explode()。

$post = explode('<!--more-->', $text, 2);
return array(Typecho_Common::fixHtml($post[0]), isset($post[1]) ? Typecho_Common::fixHtml($post[1]) : NULL);

键盘快捷键

全局

?
快捷键帮助
/或⌘K
搜索
gh
首页
ga
归档
gt
标签
gc
分类
gg
回到顶部
G
跳到底部
h
较新一篇 / 上一页
l
较旧一篇 / 下一页
Esc
关闭弹窗

文章列表首页、归档、标签、分类

j
选中下一篇
k
选中上一篇
o或Enter
打开选中的文章

阅读文章和其他页面

j
向下滚动
k
向上滚动
yy
复制本页链接
c
跳到留言