Home > Backend Development > PHP Tutorial > How Can I Truncate PHP Strings to the Nearest Word Without Mid-Word Cuts?

How Can I Truncate PHP Strings to the Nearest Word Without Mid-Word Cuts?

DDD
Release: 2024-12-10 16:54:16
Original
697 people have browsed it

How Can I Truncate PHP Strings to the Nearest Word Without Mid-Word Cuts?

Truncating PHP Strings to the Nearest Word

Truncating a string to a specific character limit can result in an unsightly cutoff mid-word. To cater to this need, we explore a PHP code snippet that accurately truncates text at the end of the closest word.

Solution 1: Using Wordwrap

The wordwrap function can split text into lines based on the specified maximum width, breaking at word boundaries. To achieve the desired truncation, we can simply utilize the first line from the split text:

$truncated = substr($string, 0, strpos(wordwrap($string, $limit), "\n"));
Copy after login

Solution 2: Token-Based Truncation

However, solution 1 has a limitation: it prematurely cuts the text if a newline character appears before the cutoff point. To mitigate this, we can implement token-based truncation:

function tokenTruncate($string, $limit) {
  $tokens = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);

  $length = 0;
  $lastToken = 0;
  while ($length <= $limit && $lastToken < count($tokens)) {
    $length += strlen($tokens[$lastToken]);
    $lastToken++;
  }

  return implode(array_slice($tokens, 0, $lastToken));
}
Copy after login

Conclusion

By implementing these solutions, you can effectively truncate PHP strings at the nearest word, ensuring a clean and meaningful display.

The above is the detailed content of How Can I Truncate PHP Strings to the Nearest Word Without Mid-Word Cuts?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template