Add to Favorites

PHP substring to shorten your output for preview

Many sites have a flow where the user is directed to a larger list of items that he can look over as a preview before navigating to a details page containing the full view. If you want to show a little preview of a long text attached to your listing, such as a user bio, using substring is a must.

It is very simple to do, feed in your string you want to shorten into substr like so substr($string,0,250). The parameters are very simple ( string to slice up, starting index, number of letters to cut ). This will give you a string who is shortened to just 250 characters in length. You can then do an extra check and append some ellipses when you truncate the string.

Doing substr($string,0,250) . ( strlen($string) > 250 ? '...' : '' );

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up