Get first n characters of a string - The Multibyte extension can come in if you need control over the string charset.
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.
javascript code
$string = substr($string,0,10).'...‘
Update:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
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.
javascript code
class Fun
{
public function limit_text($text, $len)
{
if (strlen($text) < $len)
{
return $text;
}
$text_words = explode(' ', $text);
$out = null;
foreach ($text_words as $word)
{
if ((strlen($word) > $len) && $out == null)
{
return substr($word, 0, $len) . "...";
}
if ((strlen($out) + strlen($word)) > $len)
{
return $out . "...";
}
$out.=" " . $word;
}
return $out;
}
}
If you want to cut being careful to don’t split words you can do the following
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.
Add Comment