:::

7-3 製作文章摘要

  1. 文章摘要通常就是擷取固定幾個自來當作摘要,因此,我們一樣請AI來製作:
    請用PHP8設計一個函數,可以傳入大量字串,並傳回指定字數的字串,需能支援中英文。

     

  2. 得到的函數如下,請將之加入到 index.php 的最後面:
    function truncate_string(string $string, int $length, string $append = '...'): string
    {
        // 如果字串長度小於或等於指定長度,直接返回原字串
        if (mb_strlen($string, 'UTF-8') <= $length) {
            return $string;
        }
    
        // 使用 mb_substr 截取指定長度的字串
        $truncated = mb_substr($string, 0, $length, 'UTF-8');
    
        // 檢查最後一個字符是否為空白字符
        $lastChar = mb_substr($truncated, -1, 1, 'UTF-8');
        if (mb_strwidth($lastChar, 'UTF-8') === 0) {
            $truncated = mb_substr($truncated, 0, -1, 'UTF-8');
        }
    
        // 添加省略號
        return $truncated . $append;
    }

     

  3. 接著修改 all() 函數,多加一個 $row['summary'] 的元素:
    function all(int $start = 0, int $limit = 10): array
    {
        global $pdo;
    
        ...略...
    
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            ...略...
    
            $row['media_json']  = convertMediaToJson($row['media']);
            $row['main_image']  = array_key_first($row['media']);
            $row['thumb_image'] = reset($row['media']);
            $row['summary'] = truncate_string($row['news_content'], 200);
            $results[] = $row;
        }
    
        return $results;
    }

     

  4. 最後修改 templates/main.tpl 樣板檔,非第一則新聞時,其 content 值為 $news.summary
    {foreach $all_news as $key => $news}
        {if $key==0}
            {include file="article.tpl" slider=true title=$news.news_title date=$news.report_date school=$news.school_name count=$news.views author=$news.publisher content=$news.news_content link=$news.related_link thumb=""}
        {else}
            {include file="article.tpl" slider=false title=$news.news_title date=$news.report_date school=$news.school_name count=$news.views author=$news.publisher content=$news.summary link=$news.related_link thumb=$news.thumb_image}
        {/if}
    {/foreach}
    

     

  5. 這樣就完成了!
  6. 我們還可以修改一下 templates/article.tpl,點標題連結就可以進入觀看該新聞:
    <article class="my-4">
        {if $slider}
            {include file="slider.tpl"}
        {/if}
    
        <h2><a href="index.php?id={$news.id}" class="text-decoration-none">{$title}</a></h2>
        ...略...
    </article>
    

     

  7. 如此,標題就可以點囉~

:::

書籍目錄

展開 | 闔起

快速登入


https%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D2027%26tbsn%3D55

計數器

今天: 3769376937693769
昨天: 2489248924892489
總計: 8025751802575180257518025751802575180257518025751