How to Truncate a string in PHP to the word closest to a certain number of characters?

To truncate a string in PHP to the word closest to a certain number of characters, you can use the following code:

<?php

function truncate_string_at_word($string, $max_chars)
{
  $string = trim($string);
  if (strlen($string) > $max_chars) {
    $string = substr($string, 0, $max_chars);
    $pos = strrpos($string, " ");
    if ($pos === false) {
      return $string;
    }
    return substr($string, 0, $pos);
  } else {
    return $string;
  }
}

This function takes a string and a maximum number of characters as arguments. It first trims the string to remove any leading or trailing whitespace. Then it checks if the length of the string is greater than the maximum number of characters. If it is, it uses the substr function to get a substring of the original string that is up to the maximum number of characters.

Watch a course Learn object oriented PHP

Next, it uses the strrpos function to find the position of the last occurrence of a space character in the truncated string. If a space is found, the function returns the substring from the beginning of the original string up to the position of the space. If a space is not found, the function returns the truncated string as is. If the length of the original string is less than or equal to the maximum number of characters, the function simply returns the original string.

You can then use the function like this:

<?php

function truncate_string_at_word($string, $max_chars)
{
  $string = trim($string);
  if (strlen($string) > $max_chars) {
    $string = substr($string, 0, $max_chars);
    $pos = strrpos($string, " ");
    if ($pos === false) {
      return $string;
    }
    return substr($string, 0, $pos);
  } else {
    return $string;
  }
}

$original_string = "This is a very long string that needs to be truncated.";
$max_chars = 20;
$truncated_string = truncate_string_at_word($original_string, $max_chars);
echo $truncated_string; // outputs "This is a very long"