2

Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:

$string = "this is a string";

How could I trim it to say:

$newstring = "this is";

This is what I have so far, using chunk_split(), but it isn't working. Can anyone improve on my method?

function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}

I also looked at this question, but I don't really understand it.

Community
  • 1
  • 1
imulsion
  • 8,820
  • 20
  • 54
  • 84
  • Possible duplicate of http://stackoverflow.com/q/15705059/ – HamZa Apr 29 '13 at 12:37
  • no, I am not using regex. – imulsion Apr 29 '13 at 12:38
  • The accepted answer isn't a regex solution :) – HamZa Apr 29 '13 at 12:38
  • Imulsion, the answer there is way better than those below. The answers below will cut off the word and you may get something like `this is a str` which isn't what you want. Therefor the answer in the link I provided is suited, it won't cut off a string in the middle, just remove the `$theExcerpt .= '...';` part. – HamZa Apr 29 '13 at 12:43

10 Answers10

14
if (strlen($yourString) > 15) // if you want...
{
    $maxLength = 14;
    $yourString = substr($yourString, 0, $maxLength);
}

will do the job.

Take a look here.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
DonCallisto
  • 29,419
  • 9
  • 72
  • 100
6

You didn't say the reason for this but think about what you want to achieve. Here is a function for shorten a string word by word with or without adding ellipses at the end:

function limitStrlen($input, $length, $ellipses = true, $strip_html = true) {
    //strip tags, if desired
    if ($strip_html) {
        $input = strip_tags($input);
    }

    //no need to trim, already shorter than trim length
    if (strlen($input) <= $length) {
        return $input;
    }

    //find last space within length
    $last_space = strrpos(substr($input, 0, $length), ' ');
    if($last_space !== false) {
        $trimmed_text = substr($input, 0, $last_space);
    } else {
        $trimmed_text = substr($input, 0, $length);
    }
    //add ellipses (...)
    if ($ellipses) {
        $trimmed_text .= '...';
    }

    return $trimmed_text;
}
enenen
  • 1,967
  • 2
  • 17
  • 33
6

substr cuts words in half. Also if word contains UTF8 characters, it misbehaves. So it would be better to use mb_substr:

$string = mb_substr('word word word word', 0, 10, 'utf8').'...';

Gediminas Šukys
  • 7,101
  • 7
  • 46
  • 59
4
function trimtext($text, $start, $len)
{
    return substr($text, $start, $len);
}

You can call the function like this:

$string = trimtext("this is a string", 0, 10);

Would return:

This is a

What have you tried
  • 11,018
  • 4
  • 31
  • 45
3

substr let's you take a portion of string consisting of exactly as much characters as you need.

pilsetnieks
  • 10,330
  • 12
  • 48
  • 60
3

You can use this

substr()

function to get substring

chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
3

If you want to get a string with a certain number of characters you can use substr, i.e.

$newtext = substr($string,0,$length); 

where $length is the given length of the new string.

0

If you want an abstract for the first 10 words (you can use html in $text, before script there is strip_tags) use this code:

preg_match('/^([^.!?\s]*[\.!?\s]+){0,10}/', strip_tags($text), $abstract);
echo $abstract[0];
Brucee
  • 110
  • 2
0

My function has some length to it, but I like to use it. I convert the string int to a Array.

function truncate($text, $limit){
    //Set Up
    $array = [];
    $count = -1;
    //Turning String into an Array
    $split_text = explode(" ", $text);
    //Loop for the length of words you want
    while($count < $limit - 1){
      $count++;
      $array[] = $split_text[$count];
    }
    //Converting Array back into a String
    $text = implode(" ", $array);

    return $text." ...";

  }

Or if the text is coming from an editor and you want to strip out the HTML tags.

function truncate($text, $limit){
    //Set Up
    $array = [];
    $count = -1;
    $text = filter_var($text, FILTER_SANITIZE_STRING);

    //Turning String into an Array
    $split_text = preg_split('/\s+/', $text);
    //Loop for the length of words you want
    while($count < $limit){
      $count++;
      $array[] = $split_text[$count];
    }

    //Converting Array back into a String
    $text = implode(" ", $array);

    return $text." ...";

  }
0

With elipsis (...) only if longer - and taking care of special language-specific characters:

mb_strlen($text,'UTF-8') > 60 ? mb_substr($text, 0, 60,'UTF-8') . "…" : $text;
Fanky
  • 1,673
  • 1
  • 18
  • 20