JAVASCRIPT

[ Solved -8 Answers] JAVASCRIPT – Get first n characters of a string

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):
javascript code
$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
  • 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:

javascript code
function truncate($string, $length, $dots = "...") 
{
    return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
  • We prefer this function which prevents breaking the string in the middle of a word using the wordwrap function:
javascript code
function truncate($string,$length=100,$append="…") 
{
  $string = trim($string);

  if(strlen($string) > $length) 
{
    $string = wordwrap($string, $length);
    $string = explode("\n", $string, 2);
    $string = $string[0] . $append;
  }

  return $string;
}

  • This has been built into PHP since version 4.0.6.

from the docs: http://www.php.net/manual/en/function.mb-strimwidth.php

javascript code
echo mb_strimwidth("Hello World", 0, 10, "...");

// outputs Hello W...

  • The Multibyte extension can come in handy, if you need control over the string charset.
javascript code
$charset = 'UTF-8';
$length = 10;
$string = 'Hai to yoo! I like yoo soo!';
if(mb_strlen($string, $charset) > $length) 
{
  $string = mb_substr($string, 0, $length - 3, $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.
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
javascript code
function ellipse($str,$n_chars,$crop_str=' [...]')
{
    $buff=strip_tags($str);
    if(strlen($buff) > $n_chars)
    {
        $cut_index=strpos($buff,' ',$n_chars);
        $buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
    }
    return $buff;
}
  • 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.
READ  [ Solved -7 Answers] - How to remove non-alphanumeric characters from a string

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.
javascript code
$str = 'someLongString';
$max = 7;

if(strlen($str) > $max) 
{
   $str = substr($str, 0, $max) . '...';
}
  • wordwrap won’t trim the string down, just split it up…

  • Here we use function:
javascript code
 function str_short($string,$limit)
 {
            $len=strlen($string);
            if($len>$limit)
  {
             $to_sub=$len-$limit;
             $crop_temp=substr($string,0,-$to_sub);
             return $crop_len=$crop_temp."...";
 }
            else
 {
                return $string;
            }
        }
  •  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.

Sample code:

javascript code
function cutAfter($string, $len = 30, $append = '...') 
{
        return (strlen($string) > $len) ? 
          substr($string, 0, $len - strlen($append)) . $append : 
          $string;
}

 

About the author

Venkatesan Prabu

Venkatesan Prabu

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

Click here to post a comment