How to Truncate a string in PHP to the word closest to a certain number of characters?

前端 未结 27 1440
猫巷女王i
猫巷女王i 2020-11-22 07:28

I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy artic

27条回答
  •  無奈伤痛
    2020-11-22 07:59

    I create a function more similar to substr, and using the idea of @Dave.

    function substr_full_word($str, $start, $end){
        $pos_ini = ($start == 0) ? $start : stripos(substr($str, $start, $end), ' ') + $start;
        if(strlen($str) > $end){ $pos_end = strrpos(substr($str, 0, ($end + 1)), ' '); } // IF STRING SIZE IS LESSER THAN END
        if(empty($pos_end)){ $pos_end = $end; } // FALLBACK
        return substr($str, $pos_ini, $pos_end);
    }
    

    Ps.: The full length cut may be less than substr.

提交回复
热议问题