Question

On each page of my website, I have a variable I define as the "description", and this can be either long or short, and I intend to use it for meta description as well.

I was looking around for how I can automatically cut off the extra length in the defined description variable, so it will properly fit in the meta description. I searched and found this: http://www.php.net/manual/en/function.substr.php

I can't say I understand enough to develop a solution.

To exemplify what I'm trying to do:

<?php
$description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam nec dapibus leo, vitae euismod eros. Morbi lectus dolor, iaculis id ligula ut, rutrum viverra mauris. Nam ac malesuada velit. Morbi sit amet dui dapibus, ultrices libero fringilla, feugiat lectus.";
?>

I have to truncate on the final word of $description after 190 characters, and suffix the final word with "...". Like so:

"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam nec dapibus leo, vitae euismod eros. Morbi lectus dolor, iaculis id ligula ut, rutrum viverra mauris. Nam ac malesuada velit. Morbi..."

And to find the way to write out the echo to produce the above:

<?php echo $description(truncated); ?>
Was it helpful?

Solution

You want to use the mb_strimwidth function. As per the documentation example:

<?php echo mb_strimwidth($description, 0, 190, "..."); ?>

OTHER TIPS

without mbstring:

$truncated = preg_replace('/^(.{190}[^[:punct:]\s]*).*$/', '\\1', $description);
if ( strlen($truncated) < strlen($description) -2 ) {
    // result shouldn't be longer than original
    $truncated .= '...';
}

echo $truncated;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top