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

前端 未结 27 1124
猫巷女王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 08:18

    While this is a rather old question, I figured I would provide an alternative, as it was not mentioned and valid for PHP 4.3+.

    You can use the sprintf family of functions to truncate text, by using the %.ℕs precision modifier.

    A period . followed by an integer who's meaning depends on the specifier:

    • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
    • For g and G specifiers: this is the maximum number of significant digits to be printed.
    • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string

    Simple Truncation https://3v4l.org/QJDJU

    $string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var_dump(sprintf('%.10s', $string));
    

    Result

    string(10) "0123456789"
    

    Expanded Truncation https://3v4l.org/FCD21

    Since sprintf functions similarly to substr and will partially cut off words. The below approach will ensure words are not cutoff by using strpos(wordwrap(..., '[break]'), '[break]') with a special delimiter. This allows us to retrieve the position and ensure we do not match on standard sentence structures.

    Returning a string without partially cutting off words and that does not exceed the specified width, while preserving line-breaks if desired.

    function truncate($string, $width, $on = '[break]') {
        if (strlen($string) > $width && false !== ($p = strpos(wordwrap($string, $width, $on), $on))) {
            $string = sprintf('%.'. $p . 's', $string);
        }
        return $string;
    }
    var_dump(truncate('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', 20));
    
    var_dump(truncate("Lorem Ipsum is simply dummy text of the printing and typesetting industry.", 20));
    
    var_dump(truncate("Lorem Ipsum\nis simply dummy text of the printing and typesetting industry.", 20));
    

    Result

    /* 
    string(36) "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"  
    string(14) "Lorem Ipsum is" 
    string(14) "Lorem Ipsum
    is" 
    */
    

    Results using wordwrap($string, $width) or strtok(wordwrap($string, $width), "\n")

    /*
    string(14) "Lorem Ipsum is"
    string(11) "Lorem Ipsum"
    */
    
    0 讨论(0)
  • 2020-11-22 08:18

    Use this:

    the following code will remove ','. If you have anyother character or sub-string, you may use that instead of ','

    substr($string, 0, strrpos(substr($string, 0, $comparingLength), ','))
    

    // if you have another string account for

    substr($string, 0, strrpos(substr($string, 0, $comparingLength-strlen($currentString)), ','))
    
    0 讨论(0)
  • 2020-11-22 08:19

    Here is my function based on @Cd-MaN's approach.

    function shorten($string, $width) {
      if(strlen($string) > $width) {
        $string = wordwrap($string, $width);
        $string = substr($string, 0, strpos($string, "\n"));
      }
    
      return $string;
    }
    
    0 讨论(0)
提交回复
热议问题