skip to Main Content

A develper wrote the following PHP code to create the post excerpt, as below:

/* This function allows for the auto-creation of post excerpts
======================================================================== */
function truncate_post_simple($amount,$quote_after=false) {
  $truncate = get_the_content();
  $truncate = strip_shortcodes( $truncate );
  $truncate = strip_tags($truncate);
  $truncate = substr($truncate, 0, strrpos(substr($truncate, 0, $amount), ' '));
  echo $truncate;
  echo "...";
  if ($quote_after) echo('');
}

I cannot understand the following line:

$truncate = substr($truncate, 0, strrpos(substr($truncate, 0, $amount), ' '));

It seems that the extraction is the first part of the post with $amount of characters, and then it will remove an extra part that beginning with a space.

I cannot understand why he will do this. Why don’t use

$truncate = substr($truncate, 0, $amount);

directly, or if he wants to remove extra spaces, using:

$truncate = $rtrim(substr($truncate, 0, $amount));

2

Answers


  1. It looks like they were trying to find the last space before the $amount-th character to be truncated. This way, a word is not clipped in the middle. You can break it down as follows:

    // finds the last space in $truncate before the $amount-th character
    $lastSpace = strrpos(substr($truncate, 0, $amount), ' ');
    // truncate the string to the last space
    $truncate = substr($truncate, 0, $lastSpace);
    

    Some examples may help:

    $truncate = "The quick brown fox jumps over the lazy dog";
    $amount = 12;
    $lastSpace = strrpos(substr($truncate, 0, $amount), ' '); // 9
    $result = substr($truncate, 0, $lastSpace); // "The quick"
    

    If we had just used $amount directly, the word "brown" would have been
    clipped in the middle

    $result = substr($truncate, 0, $amount); // "The quick br";
    
    Login or Signup to reply.
  2. Spread it out and annotate it.

    $truncate = substr( // substring from 0 until the first space before $amount
      $truncate,
      0,
      strrpos( // position of the first space, counted from the end of the substring.
        substr( // blind substring of length $amount, starting from 0
          $truncate,
          0,
          $amount
        ),
        ' '
      )
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search