How can I get the first n characters of a string in PHP? What’s the fastest way to trim a string to a specific number of characters, and append ‘…’ if needed?
Share
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.
Update:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by ‘…’
Update 2:
Or as function:
Update 3:
It’s been a while since I wrote this answer and I don’t actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the
wordwrapfunction: