Home >Backend Development >PHP Tutorial >How Can I Truncate Strings in PHP to the Nearest Word?

How Can I Truncate Strings in PHP to the Nearest Word?

Linda Hamilton
Linda HamiltonOriginal
2024-12-23 14:44:13533browse

How Can I Truncate Strings in PHP to the Nearest Word?

Truncating Strings in PHP to the Nearest Word

To crop a string at the end of the last word before a specified character count, PHP provides several methods.

Using wordwrap Function:

The wordwrap function divides text into multiple lines with a maximum width, automatically breaking at word boundaries. By taking only the first line, you can truncate the text to the nearest word:

$truncated_string = substr($string, 0, strpos(wordwrap($string, $desired_width), "\n"));

Edge Case Handling:

This method doesn't handle texts shorter than the desired width. For that, use the following:

if (strlen($string) > $desired_width) {
    $string = substr($string, 0, strpos(wordwrap($string, $desired_width), "\n"));
}

Token Truncation:

To resolve potential issues with newlines in the text, this method splits the text into tokens (words, whitespace, and newlines) and accumulates their lengths:

function tokenTruncate($string, $desired_width) {
    $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
    $length = 0;
    $last_part = 0;
    for (; $last_part < count($parts); ++$last_part) {
        $length += strlen($parts[$last_part]);
        if ($length > $desired_width) { break; }
    }
    return implode(array_slice($parts, 0, $last_part));
}

This method also handles UTF8 characters.

Unit Testing:

class TokenTruncateTest extends PHPUnit_Framework_TestCase {
    // ... test cases ...
}

Additional Notes:

  • This method relies on word boundaries.
  • Handling special characters like emojis or different languages may require additional considerations.

The above is the detailed content of How Can I Truncate Strings in PHP to the Nearest Word?. 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