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

前端 未结 27 1123
猫巷女王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:12

    Based on @Justin Poliey's regex:

    // Trim very long text to 120 characters. Add an ellipsis if the text is trimmed.
    if(strlen($very_long_text) > 120) {
      $matches = array();
      preg_match("/^(.{1,120})[\s]/i", $very_long_text, $matches);
      $trimmed_text = $matches[0]. '...';
    }
    
    0 讨论(0)
  • 2020-11-22 08:12

    Added IF/ELSEIF statements to the code from Dave and AmalMurali for handling strings without spaces

    if ((strpos($string, ' ') !== false) && (strlen($string) > 200)) { 
        $WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), ' ')); 
    } 
    elseif (strlen($string) > 200) {
        $WidgetText = substr($string, 0, 200);
    }
    
    0 讨论(0)
  • 2020-11-22 08:13

    I believe this is the easiest way to do it:

    $lines = explode('♦♣♠',wordwrap($string, $length, '♦♣♠'));
    $newstring = $lines[0] . ' • • •';
    

    I'm using the special characters to split the text and cut it.

    0 讨论(0)
  • 2020-11-22 08:15
    $WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), ' '));
    

    And there you have it — a reliable method of truncating any string to the nearest whole word, while staying under the maximum string length.

    I've tried the other examples above and they did not produce the desired results.

    0 讨论(0)
  • $shorttext = preg_replace('/^([\s\S]{1,200})[\s]+?[\s\S]+/', '$1', $fulltext);
    

    Description:

    • ^ - start from beginning of string
    • ([\s\S]{1,200}) - get from 1 to 200 of any character
    • [\s]+? - not include spaces at the end of short text so we can avoid word ... instead of word...
    • [\s\S]+ - match all other content

    Tests:

    1. regex101.com let's add to or few other r
    2. regex101.com orrrr exactly 200 characters.
    3. regex101.com after fifth r orrrrr excluded.

    Enjoy.

    0 讨论(0)
  • 2020-11-22 08:16

    Here you go:

    function neat_trim($str, $n, $delim='…') {
       $len = strlen($str);
       if ($len > $n) {
           preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
           return rtrim($matches[1]) . $delim;
       }
       else {
           return $str;
       }
    }
    
    0 讨论(0)
提交回复
热议问题