Home >Backend Development >PHP Tutorial >How Can I Efficiently Trim Strings to a Specified Length in PHP and Avoid Mid-Word Breaks?

How Can I Efficiently Trim Strings to a Specified Length in PHP and Avoid Mid-Word Breaks?

Barbara Streisand
Barbara StreisandOriginal
2024-12-23 22:30:15184browse

How Can I Efficiently Trim Strings to a Specified Length in PHP and Avoid Mid-Word Breaks?

Trimming Strings with Dots in PHP: A Comprehensive Guide

Need to condense strings in your PHP code? Here's how you can truncate a string to a specified number of characters and append ellipsis (...) if characters are removed.

The Swift Solution:

$string = substr($string, 0, 10) . '...';

This simple method retrieves the first ten characters of the string, followed by ellipsis if necessary.

Optimized Approach:

$string = (strlen($string) > 13) ? substr($string, 0, 10) . '...' : $string;

This updated version includes a check to ensure the resulting string is the desired length. If the original string exceeds 13 characters, it is truncated to 10 characters and followed by ellipsis. Otherwise, the original string remains untrimmed.

Functional Abstraction:

function truncate($string, $length, $dots = "...") {
    return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}

This function encapsulates the trimming logic, allowing you to reuse it with different parameters. It takes three arguments: the string to be trimmed, the desired length, and an optional ellipsis string.

Avoiding Mid-Word Breakage:

function truncate($string, $length = 100, $append = "…") {
  $string = trim($string);

  if (strlen($string) > $length) {
    $string = wordwrap($string, $length);
    $string = explode("\n", $string, 2);
    $string = $string[0] . $append;
  }

  return $string;
}

This enhanced function utilizes wordwrap to prevent breaking strings mid-word. If the string is longer than the specified length, it is word-wrapped and truncated at the nearest whitespace.

The above is the detailed content of How Can I Efficiently Trim Strings to a Specified Length in PHP and Avoid Mid-Word Breaks?. 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