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
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:Some examples may help:
If we had just used
$amount
directly, the word "brown" would have beenclipped in the middle
Spread it out and annotate it.