Here’s how you can grab the first 155 characters (or whatever number of characters you want) of a string of text, but respect the boundaries of complete sentences that fit within the characters limit.

Basically, we just want to chop off any sentence that passes over the character limit we specify, which in the example below is 155 characters, but could be whatever you want.

$description = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eget lectus mi. Maecenas id urna purus. Sed consequat mauris id rutrum gravida. Fusce et lobortis odio. Sed euismod suscipit mauris sed tincidunt. Donec vel risus orci. Curabitur porta, est aliquam dignissim luctus, diam mauris eleifend mauris, non convallis sem justo at metus. Curabitur tempor vestibulum ipsum nec tincidunt. Praesent molestie eros sit amet maximus euismod. Donec venenatis commodo ex, et rutrum ex convallis at. Nunc eget urna id quam suscipit pellentesque vitae ac dui. Sed mauris sapien, vestibulum eget bibendum eget, efficitur eget purus. Nullam faucibus blandit pharetra. Nullam ac luctus magna.';

if( strlen( $description ) > 155 ) {
    $description = substr( $description, 0, strrpos( $description, '. ', 155 - strlen( $description ) ) + 1 );
    echo $description;
} else {
    echo $description;
}

Then, you can do whatever you want with it. If it’s less than 155 characters, or whatever you set it to, you can just echo the original output in the else statement.

Strip Tags from Output

If you’ll be using this for something like a meta or opengraph tag and pulling from a WYSIWYG field that could potentially hold HTML tags, make sure to strip them from the output by adding in the PHP html_entity_decode() and strip_tags() functions, or you’re gonna have a bad time:

$description = '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. <em>Cras eget lectus mi. Maecenas id urna purus.</em> Sed consequat mauris id rutrum gravida. Fusce et lobortis odio. <strong>Sed euismod</strong> suscipit mauris sed tincidunt. Donec vel risus orci. Curabitur porta, est aliquam dignissim luctus, diam mauris eleifend mauris, non convallis sem justo at metus. Curabitur tempor vestibulum ipsum nec tincidunt. <span class="some-class">Praesent molestie</span> eros sit amet maximus euismod. Donec venenatis commodo ex, et rutrum ex convallis at. Nunc eget urna id quam suscipit pellentesque vitae ac dui. Sed mauris sapien, vestibulum eget bibendum eget, efficitur eget purus. Nullam faucibus blandit pharetra. Nullam ac luctus magna.</p>';

$description = html_entity_decode( strip_tags( $description ) );

if( strlen( $description ) > 155 ) {
    $description = substr( $description, 0, strrpos( $description, '. ', 155 - strlen( $description ) ) + 1 );
    echo $description;
} else {
    echo $description;
}

Leave a Reply

Your email address will not be published.

Continue Reading