How to Truncate a string in PHP to the word closes

2018-12-31 08:20发布

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 article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last word before 200 chars.

26条回答
人间绝色
2楼-- · 2018-12-31 08:23

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);
}
查看更多
若你有天会懂
3楼-- · 2018-12-31 08:23

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)), ','))
查看更多
步步皆殇っ
4楼-- · 2018-12-31 08:24

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]. '...';
}
查看更多
情到深处是孤独
5楼-- · 2018-12-31 08:26

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.

查看更多
弹指情弦暗扣
6楼-- · 2018-12-31 08:27

I have a function that does almost what you want, if you'll do a few edits, it will fit exactly:

<?php
function stripByWords($string,$length,$delimiter = '<br>') {
    $words_array = explode(" ",$string);
    $strlen = 0;
    $return = '';
    foreach($words_array as $word) {
        $strlen += mb_strlen($word,'utf8');
        $return .= $word." ";
        if($strlen >= $length) {
            $strlen = 0;
            $return .= $delimiter;
        }
    }
    return $return;
}
?>
查看更多
骚的不知所云
7楼-- · 2018-12-31 08:28

This will return the first 200 characters of words:

preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, 201));
查看更多
登录 后发表回答