I’m pulling blog posts from a DB. I want to trim the text to a max length of 340 characters.
If the blog post is over 340 characters I want to trim the text to the last full word and add ‘…’ on the end.
E.g.
NOT: In the begin....
BUT: In the ...
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The other answers show you how you can make the text roughly 340 characters. If that’s fine for you, then use one of the other answers.
But if you want a very strict maximum of 340 characters, the other answers won’t work. You need to remember that adding the
'...'can increase the length of the string and you need to take account of that.Note also that here I’m using the overload of
strrposthat takes an offset to start searching directly from the correct location in the string, rather than first shortening the string.See it working online: ideone