可说欢喜
Typecho

typecho 文章字数统计

by 温柔, 2023-02-18


同样是移植主题时遇到需要实现的效果

functions.php 文件添加下面代码

function t_count($cid) {
    $db = Typecho_Db::get();
    $row = $db->fetchRow ($db->select ('table.contents.text')->from ('table.contents')->where ('table.contents.cid=?',$cid)->order ('table.contents.cid',Typecho_Db::SORT_ASC)->limit (1));
    $text = $row['text'];
    $text = mb_convert_encoding($text, 'UTF-8', 'auto');
    $text = str_replace('/( |\s|\r\n|\n|\r)+/u', '', $text);
    $text = preg_replace('/[^\x{4e00}-\x{9fa5}]/u', '', $text);
    $count = mb_strlen($text, 'UTF-8');
    return $count;
}

前台调用方法:

<?php echo t_count($this->cid); ?>

后面发现网上有现成的代码:
文章中文字数统计
[来自泽泽社长 https://blog.zezeshe.com/archives/typecho-function.html]

function  art_count ($cid){
    $db=Typecho_Db::get ();
    $rs=$db->fetchRow ($db->select ('table.contents.text')->from ('table.contents')->where ('table.contents.cid=?',$cid)->order ('table.contents.cid',Typecho_Db::SORT_ASC)->limit (1));
    $text = preg_replace("/[^\x{4e00}-\x{9fa5}]/u", "", $rs['text']);
    echo mb_strlen($text,'UTF-8');
}

模板引用<?php echo art_count($this->cid); ?>

typecho代码
温柔

作者: 温柔

2024 © typecho & elise