Typecho获取文章所有图片

时间:2016-04-21
由于需要获取文章所有图片,但是Typecho不支持该功能,所以自己用正则实现了下。本文章向码农介绍Typecho获取文章所有图片,希望对码农有一定的帮助。

看到很多在Typecho和wordpress之间选择的文章,对于我来说,WP的生态圈无疑更丰富,但是都是PHP实现的,typecho只是有些函数没有实现而已。即:

世上本没有路 走的人多了也便成了路

我选择typecho的理由很简单,Markdown和简单

 

1.获取文章图片

函数

function img_postthumb($content) {
   preg_match_all("/\<img.*?src\=\"(.*?)\"[^>]*>/i", $content, $thumbUrl);  //通过正则式获取图片地址
   $img_src = $thumbUrl[1][0];  //将赋值给img_src
   $img_counter = count($thumbUrl[0]);  //一个src地址的计数器
    if($img_counter > 0){
        for($i=0;$i<$img_counter;$i++){
            echo "<img class='thumbimg' src='".$thumbUrl[1][$i]."' />";
        }
    }   
}

使用

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

参考获取文章第一张图片(缩略图)

当然获取了图片,同样需要只获取内容

2.只获取内容(去除图片)

使用

<?php echo $str = preg_replace('~<img(.*?)>~','',$this->content);?>

3.判断文章标签

<?php $tags=$this->tags;if($tags!=null&&in_array("say",$tags[0])){ ?>  
...  //这个用来判断首页的说说,定义不同的样式
<?php } ?>

4.判断文章分类

<?php if($this->category == "say"): ?>
... //自带的判断分类
<?php endif; ?>

5.日期格式化

函数

function time_tran($the_time) {
    $the_time=date("Y-m-d H:i:s",$the_time);
    $now_time = date("Y-m-d H:i:s", time());
    $now_time = strtotime($now_time);
    $show_time = strtotime($the_time);
    $dur = $now_time - $show_time;
    if ($dur < 0) {
        return $the_time;
    } else {
        if ($dur < 60) {
            return $dur . '秒前';
        } else {
            if ($dur < 3600) {
                return floor($dur / 60) . '分钟前';
            } else {
                if ($dur < 86400) {
                    return floor($dur / 3600) . '小时前';
                } else {
                    if ($dur < 2592000) {//3天内
                        return floor($dur / 86400) . '天前';
                    } else {
                        return $the_time;
                    }
                }
            }
        }
    }
}

使用

<?php echo time_tran($this->date->timeStamp); ?>