How can we 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?
//The simple version for 10 Characters from the beginning of the string.
- 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 ‘…’
Or as function:
- We prefer this function which prevents breaking the string in the middle of a word using the wordwrap function:
- This has been built into PHP since version 4.0.6.
from the docs: http://www.php.net/manual/en/function.mb-strimwidth.php
- The Multibyte extension can come in handy, if you need control over the string charset.
- Sometimes, you need to limit the string to the last complete word ie: you don’t want the last word to be broken instead you stop with the second last word.
- eg: we need to limit “This is my String” to 6 chars but instead of ‘This i…” we want it to be ‘This…” ie we will skip that broken letters in the last word.
- If you want to cut being careful to don’t split words you can do the following
- if $str is shorter than $n_chars returns it untouched.
- If $str is equal to $n_chars returns it as is as well.
- if $str is longer than $n_chars then it looks for the next space to cut or (if no more spaces till the end) $str gets cut rudely instead at $n_chars.
NOTE: be aware that this method will remove all tags in case of HTML.
- substr() would be best, you’ll also want to check the length of the string first.
- wordwrap won’t trim the string down, just split it up…
- Here we use function:
- you just call the function with string and limit.
- eg: str_short(“hahahahahah”,5);
- it will cut of your string and add “…” at the end.