问题描述:

This question already has an answer here:

  • How to capture complete words using substr() in PHP, limit by word?

    6 answers

网友答案:
$text = "This should just fit in! But if we make it longer, it won't ";
if (strlen($text) > 50) {
    $text = substr($text, 0, 50);
    for ($i = strlen($text) - 1; $i > 0; $i--) {
        if ($text[$i] === ' ' || $text[$i] === ',' || $text[$i] === '.' || $text[$i] === '!' || $text[$i] === '?') {
            $text = substr($text, 0, $i) . '... <b>Read More</b>';
            break;
        }
    }
}

Does the job for me (should add RegEx, but I'm not that great with those...).

网友答案:

ord() returns an integer, but you check the value of $ascii using !== and compare it with a string. As opposed to !=, !== is only true if the types of the operands match too.

In addition, to extract a single character from the string, specify a length for the substring:

$chr = substr($short,$x,1);

You may also index the string directly: $chr = $short{$x}

Edit: Found two flaws more:

The second line should be:

$short = substr($row_object_title, 0, 50);

(You've missed the offset before the length parameter.)

Furthermore you're appending '...' to the original string, not to the shortened version. Below is a complete version of the (hopefully) corrected script.

if (strlen($row_object_title) > 50){
    // check for spaces
        $short = substr($row_object_title,50);

        $chr = substr($short,-1);
        $ascii = ord($chr);
        if ($ascii == 32){
            $row_object_title = $short . "...";
        }else{  
            $x = 49;
            while($ascii != 32){
                $chr = substr($short,$x,1);
                $ascii = ord($chr);
                if ($ascii == 32){
                    // we got a space!
                    $row_object_title = substr($short, 0, $x) . "...";
                }
                $x = $x - 1;                        
            }

        }
}
网友答案:

If I understand your problem correctly, this should do the trick:

// if string does *not* end with one or more whitespace characters
if(!preg_match('/\s+$/',$string)) {
    // replace everything after last group of one or more whitespaces with '...'
    $string = preg_replace('/(.*)\s+.*/','\1...',$string);
}
网友答案:

I use the following function, can't remember where I found it. Clears HTML in text, and limit string to $limit characters, without breaking words.

function show_chopped_text($str, $limit)
{
    $regex = "/<\/?\w+((\s+\w+(\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)+\s*|\s*)\/?>/i";
    $strip_html = preg_replace($regex,'',$str);

    $rough_short_par = substr($strip_html, 0, $limit); 
    $last_space_pos = strrpos($rough_short_par, " ");
    $clean_short_par = substr($rough_short_par, 0, $last_space_pos);
    $clean_sentence = $clean_short_par . "..."; 
    return $clean_sentence;
}
相关阅读:
Top