<?php
function truncateGumbo($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;
}
function truncateGordon($string, $chars = 50, $terminator = ' …') {
return mb_strimwidth($string, 0, $chars, $terminator);
}
function truncateSoapBox($string, $chars = 50, $terminate = ' …')
{
$chars -= mb_strlen($terminate);
if ( $chars <= 0 )
return $terminate;
$string = mb_substr($string, 0, $chars);
$space = mb_strrpos($string, ' ');
if ($space < mb_strlen($string) / 2)
return $string . $terminate;
else
return mb_substr($string, 0, $space) . $terminate;
}
function truncateMickmackusa($string, $max = 50, $terminator = ' …') {
$trunc = $max - mb_strlen($terminator, 'UTF-8');
return preg_replace("~(?=.{{$max}})(?:\S{{$trunc}}|.{0,$trunc}(?=\s))\K.+~us", $terminator, $string);
}
$tests = [
[
'testCase' => "Answer to the Ultimate Question of Life, the Universe, and Everything.",
// 50th char ---------------------------------------------------^
'expected' => "Answer to the Ultimate Question of Life, the …",
],
[
'testCase' => "A single line of text to be followed by another\nline of text",
// 50th char ----------------------------------------------------^
'expected' => "A single line of text to be followed by another …",
],
[
'testCase' => "âãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝ",
// 50th char ---------------------------------------------------^
'expected' => "âãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđ …",
],
[
'testCase' => "123456789 123456789 123456789 123456789 123456789",
// 50th char doesn't exist -------------------------------------^
'expected' => "1234567890123456789012345678901234567890123456789",
],
[
'testCase' => "Hello worldly world",
// 50th char doesn't exist -------------------------------------^
'expected' => "Hello worldly world",
],
[
'testCase' => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWYXZ1234567890",
// 50th char ---------------------------------------------------^
'expected' => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV …",
],
];
foreach ($tests as ['testCase' => $testCase, 'expected' => $expected]) {
echo "\tSample Input:\t\t$testCase\n";
echo "\n\ttruncateGumbo:\t\t" , truncateGumbo($testCase);
echo "\n\ttruncateGordon:\t\t" , truncateGordon($testCase);
echo "\n\ttruncateSoapBox:\t" , truncateSoapBox($testCase);
echo "\n\ttruncateMickmackusa:\t" , truncateMickmackusa($testCase);
echo "\n\tExpected Result:\t{$expected}";
echo "\n-----------------------------------------------------\n";
}
preferences:
20.55 ms | 410 KiB | 5 Q