Home >Backend Development >PHP Tutorial >How to Truncate Strings to a Maximum of 20 Words in PHP?

How to Truncate Strings to a Maximum of 20 Words in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-24 05:28:10915browse

How to Truncate Strings to a Maximum of 20 Words in PHP?

Truncating Strings to a Maximum of 20 Words in PHP

In PHP, the necessity may arise to limit the length of strings to a specific number of words. This can be useful in scenarios such as creating concise summaries or displaying excerpts from longer content. To achieve this, let's explore how to truncate a string to the first 20 words in PHP.

The limit_text function is a practical tool for achieving this task. It employs a combination of built-in PHP functions to analyze and manipulate the input string:

  • str_word_count: This function counts the number of words in the string.
  • substr: This function is used to extract a portion of the original string based on the specified start and length.

Here's a concise implementation of the limit_text function:

function limit_text($text, $limit) {
    if (str_word_count($text, 0) > $limit) {
        $words = str_word_count($text, 2);
        $pos   = array_keys($words);
        $text  = substr($text, 0, $pos[$limit]) . '...';
    }
    return $text;
}

To use this function, simply pass the string you want to truncate as the first argument and specify the maximum word count as the second argument. For instance, the following code truncates a string after the first 5 words:

echo limit_text('Hello here is a long sentence that will be truncated by the', 5);

Output:

Hello here is a long ...

This code effectively limits the original string to a maximum of 5 words, indicated by the "..." (ellipsis) added to the truncated output.

The above is the detailed content of How to Truncate Strings to a Maximum of 20 Words in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn