Search code examples
phptextpunctuation

Limit text to a certain number of chars, but stop when a period is found within the final 20 chars


So, I have this function to produce an excerpt from large texts.

function excerpt( $string, $max_chars = 160, $more = '...' ) {

    if ( strlen( $string ) > $max_chars ) {

        $cut = substr( $string, 0, $max_chars );

        $string = substr( $cut, 0, strrpos( $cut, ' ' ) ) . $more;

    }

  return $string;
}

This works just fine for it's intends - it limits a given text to a certain number of chars, without cutting words.

Here's a working example:

$str = "The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.";

echo excerpt( $str, 160 );

This produces this output:

The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid...

However, I'm trying to figure out how to stop if a period, an exclamation or an interrogation mark is found within the excerpts last 20 chars. So, using the above sentence, it would produce this output:

The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer.

Any ideas how to archive this?


Solution

  • I would try the following and put this in a loop for all of your:

    // Define the characters to look for:
    $charToCheck = array(".", "!", "?");
    
    // Loop through each character to check
    foreach ( $charToCheck as $char) {
    
        // Gives you the last index of a period. Returns false if not in string
        $lastIndex = strrpos($cut, $char);
    
        // Checks if character is found in the last 20 characters of your string
        if ( $lastIndex > ($max_chars - 20)) {
            // Returns the shortened string beginning from first character
            $cut = substr($cut, 0, $lastIndex + 1);
        }
    }