Truncate a string to first n characters of a string and add three dots if any characters are removed
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';
Update:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
$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:
function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
Update 3:
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="…") {
$string = trim($string);
if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}
return $string;
}
Add ... if string is too long PHP
The PHP way of doing this is simple:
$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;
But you can achieve a much nicer effect with this CSS:
.ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
Now, assuming the element has a fixed width, the browser will automatically break off and add the ...
for you.
Smart way to truncate long strings
Essentially, you check the length of the given string. If it's longer than a given length n
, clip it to length n
(substr
or slice
) and add html entity …
(…) to the clipped string.
Such a method looks like
function truncate(str, n){
return (str.length > n) ? str.slice(0, n-1) + '…' : str;
};
If by 'more sophisticated' you mean truncating at the last word boundary of a string then you need an extra check.
First you clip the string to the desired length, next you clip the result of that to its last word boundary
function truncate( str, n, useWordBoundary ){
if (str.length <= n) { return str; }
const subString = str.slice(0, n-1); // the original check
return (useWordBoundary
? subString.slice(0, subString.lastIndexOf(" "))
: subString) + "…";
};
You can extend the native String
prototype with your function. In that case the str
parameter should be removed and str
within the function should be replaced with this
:
String.prototype.truncate = String.prototype.truncate ||
function ( n, useWordBoundary ){
if (this.length <= n) { return this; }
const subString = this.slice(0, n-1); // the original check
return (useWordBoundary
? subString.slice(0, subString.lastIndexOf(" "))
: subString) + "…";
};
More dogmatic developers may chide you strongly for that ("Don't modify objects you don't own". I wouldn't mind though).
An approach without extending the String
prototype is to create
your own helper object, containing the (long) string you provide
and the beforementioned method to truncate it. That's what the snippet
below does.
const LongstringHelper = str => {
const sliceBoundary = str => str.substr(0, str.lastIndexOf(" "));
const truncate = (n, useWordBoundary) =>
str.length <= n ? str : `${ useWordBoundary
? sliceBoundary(str.slice(0, n - 1))
: str.slice(0, n - 1)}…`;
return { full: str, truncate };
};
const longStr = LongstringHelper(`Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum`);
const plain = document.querySelector("#resultTruncatedPlain");
const lastWord = document.querySelector("#resultTruncatedBoundary");
plain.innerHTML =
longStr.truncate(+plain.dataset.truncateat, !!+plain.dataset.onword);
lastWord.innerHTML =
longStr.truncate(+lastWord.dataset.truncateat, !!+lastWord.dataset.onword);
document.querySelector("#resultFull").innerHTML = longStr.full;
body {
font: normal 12px/15px verdana, arial;
}
p {
width: 450px;
}
#resultTruncatedPlain:before {
content: 'Truncated (plain) n='attr(data-truncateat)': ';
color: green;
}
#resultTruncatedBoundary:before {
content: 'Truncated (last whole word) n='attr(data-truncateat)': ';
color: green;
}
#resultFull:before {
content: 'Full: ';
color: green;
}
<p id="resultTruncatedPlain" data-truncateat="120" data-onword="0"></p>
<p id="resultTruncatedBoundary" data-truncateat="120" data-onword="1"></p>
<p id="resultFull"></p>
Python truncate a long string
info = (data[:75] + '..') if len(data) > 75 else data
Truncate a multibyte String to n chars
Try this:
function truncate($string, $chars = 50, $terminator = ' …') {
$cutPos = $chars - mb_strlen($terminator);
$boundaryPos = mb_strrpos(mb_substr($string, 0, mb_strpos($string, ' ', $cutPos)), ' ');
return mb_substr($string, 0, $boundaryPos === false ? $cutPos : $boundaryPos) . $terminator;
}
But you need to make sure that your internal encoding is properly set.
Related Topics
What in Layman'S Terms Is a Recursive Function Using PHP
How to Explain Composer'S Error Log
How to Get a Substring Between Two Strings in PHP
How to Get a File Name from a Full Path With PHP
Get the First Element of an Array
Detect Browser Language in PHP
PHP - Check If Two Arrays Are Equal
Recursive Function to Generate Multidimensional Array from Database Result
Best Way to Get Result Count Before Limit Was Applied
Detecting Request Type in PHP (Get, Post, Put or Delete)
How to Generate in PHP All Combinations of Items in Multiple Arrays
How to Use Ajax in a Wordpress Shortcode
Facebook Graph API Not Work from 2.2 to 2.3
PHP: How to Determine Every Nth Iteration of a Loop
How to Compare Two Datetime Objects in PHP 5.2.8