91

I'm looking for a way to limit a string in php and add on ... at the end if the string was too long.

Carrie Kendall
  • 11,124
  • 5
  • 61
  • 81
Belgin Fish
  • 19,187
  • 41
  • 102
  • 131
  • You might find [`s($str)->truncate($length)`](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L233) or even [`s($str)->truncateSafely($length)`](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L246) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Str). – caw Jul 27 '16 at 01:01
  • 1
    Working example:https://stackoverflow.com/a/66662165/7186739 – Billu Mar 16 '21 at 19:34

13 Answers13

185

You can use something similar to the below:

if (strlen($str) > 10)
   $str = substr($str, 0, 7) . '...';
Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
bramp
  • 9,581
  • 5
  • 40
  • 46
  • 2
    I guess you didn't think he might be skipping his homework reading assignments. – dlamblin Jun 10 '10 at 23:43
  • 1
    Sorry no I didn't consider that. What are the rules for homework? Oh and wait, I just noticed, my code doesn't even work correctly ;) – bramp Jun 10 '10 at 23:47
  • 3
    It's just a community rule: http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer-homework-questions – dlamblin Jun 11 '10 at 00:01
  • 6
    For getting a substring of UTF-8 characters, I highly recommend mb_substr -> `mb_substr($utf8string,0,5,'UTF-8');` You would avoid wrong lenght of the slice this way. – vinsa Jun 06 '15 at 10:44
48

From php 4.0.6 , there is a function for the exact same thing

function mb_strimwidth can be used for your requirement

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
//Hello W...
?>

It does have more options though,here is the documentation for this mb_strimwidth

miken32
  • 42,008
  • 16
  • 111
  • 154
11

You can use the wordwrap() function then explode on newline and take the first part, if you don't want to split words.

$str = 'Stack Overflow is as frictionless and painless to use as we could make it.';
$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';

Source: https://stackoverflow.com/a/1104329/1060423

If you don't care about splitting words, then simply use the php substr function.

echo substr($str, 0, 28) . '...';
Manoj
  • 21,753
  • 3
  • 20
  • 41
Sev
  • 15,401
  • 9
  • 56
  • 75
10

2nd argument is where to start string and 3rd argument how many characters you need to show

$title = "This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string";
    echo substr($title,0,50);
Naeem Ijaz
  • 805
  • 9
  • 17
5
 $string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;

Or as function:

function truncate($string, $length, $dots = "...") {
    return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}

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 wordwrap function:

function truncate($string,$length=100,$append="&hellip;") {
$string = trim($string);

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

  return $string;
}
Waruna Manjula
  • 3,067
  • 1
  • 34
  • 33
3

Do a little homework with the php online manual's string functions. You'll want to use strlen in a comparison setting, substr to cut it if you need to, and the concatenation operator with "..." or "&hellip;"

dlamblin
  • 43,965
  • 20
  • 101
  • 140
1

To truncate a string provided by the maximum limit without breaking a word use this:

/**
 * truncate a string provided by the maximum limit without breaking a word
 * @param string $str
 * @param integer $maxlen
 * @return string
 */
public static function truncateStringWords($str, $maxlen): string
{
    if (strlen($str) <= $maxlen) return $str;

    $newstr = substr($str, 0, $maxlen);
    if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));

    return $newstr;
}
crmpicco
  • 16,605
  • 26
  • 134
  • 210
1

In Laravel, there is a string util function for this, and it is implemented this way:

public static function limit($value, $limit = 100, $end = '...')
{
    if (mb_strwidth($value, 'UTF-8') <= $limit) {
        return $value;
    }

    return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
}
geckob
  • 7,680
  • 5
  • 30
  • 39
1
$res = explode("\n",wordwrap('12345678910', 8, "...\n",true))[0];

// $res will be  : "12345678..."
J.F.
  • 13,927
  • 9
  • 27
  • 65
  • 2
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Donald Duck Nov 24 '20 at 12:06
0

In another way to limit a string in php and add on readmore text or like '...' using below code

if (strlen(preg_replace('#^https?://#', '', $string)) > 30) { 
    echo substr(preg_replace('#^https?://#', '', $string), 0, 35).'&hellip;'; 
}
PCMShaper
  • 54
  • 5
0
function truncateString($string, $maxlength, $ellipsis = false){

    if(mb_strlen($string) <= $maxlength){
        return $string;
    }

    if(empty($ellipsis)){
        $ellipsis = '';
    }

    if($ellipsis === true){
        $ellipsis = '…';
    }

    $ellipsis_length = mb_strlen($ellipsis);

    $maxlength = $maxlength - $ellipsis_length;

    $string = trim(mb_substr($string, 0, $maxlength)) . $ellipsis;

    return $string;

}

http://sandbox.onlinephpfunctions.com/code/968e2fd1e98b60828a12d6dc0b68ec38b3628757

Arthur Shlain
  • 961
  • 10
  • 23
0
function showAHumanDate( $dateString ){
$toRet = '';
$days = date( "d", strtotime( $dateString ) );
$month = date( "F", strtotime( $dateString ) );
$year = date( "Y", strtotime( $dateString ) );

switch( $days ){
    case '01':
    $string = '1st';
    break;
    case '02':
    $string = '2nd';
    break;
    case '03':
    $string = '3rd';
    break;
    case '21':
    $string = '21st';
    break;
    case '22':
    $string = '22nd';
    break;
    case '23':
    $string = '23rd';
    break;
    case '31':
    $string = '31st';
    break;
    default:
    $string = $days.'th';
}

// strip the month to three letters: 
$month = mb_strimwidth( $month, 0, 3, '' );

$toRet = $string.' '.$month.' '.$year;
return $toRet;

}
Pritam Pawade
  • 637
  • 7
  • 21
Damian
  • 1
  • 1
-3

$value = str_limit('This string is really really long.', 7);

// This st...

Paul Caleb
  • 177
  • 1
  • 4
  • 12