Skip to content
PHP Logo

What are the potential pitfalls of using substr() function to limit the length of a post in PHP?

Using the substr() function to limit the length of a post in PHP can potentially cut off words in the middle, resulting in incomplete or broken text. To solve this issue, we can use the substr() function in combination with strpos() to find the last space before the desired character limit and then extract the substring up to that point.

php
function limitPostLength($post, $limit) {
    if(strlen($post) <= $limit) {
        return $post;
    } else {
        $shortened = substr($post, 0, strpos($post, ' ', $limit));
        return $shortened . '...';
    }
}

$post = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$limitedPost = limitPostLength($post, 20);
echo $limitedPost;