CakeFest 2025 Madrid: The Official CakePHP Conference

Voting

: six plus one?
(Example: nine)

The Note You're Voting On

nospam at nospam dot com
9 years ago
<?php

// shortens a long string to a max length while inserting a string into the exact middle
function strShorten($str, $maxlen = 10, $insert = '/.../') {
if (
$str && !is_array($str)) { // valid string
if ($maxlen && is_numeric($maxlen) && $maxlen < strlen($str)) { // string needs shortening
if ($insert && ($ilen = strlen($insert))) { // insert string and length
if ($ilen >= $maxlen) { // insert string too long so use default insert
$insert = '**'; // short default so works even when a very small $maxlen
$ilen = 2;
}
}
$chars = $maxlen - $ilen; // number of $str chars to keep
$start = ceil($chars/2); // position to start cutting
$end = floor($chars/2); // position from end to stop cutting
return substr_replace($str, $insert, $start, -$end); // first.insert.last
} else { // string already short enough
return $str; // return original string
}
}
}

echo
strShorten('123456789', 6, ''); // outputs 123789
echo strShorten('123456789', 6, '-'); // outputs 123-89
echo strShorten('123456789', 6, 'longstring'); // outputs 12**89
echo strShorten('abcdefghijklmnopqrstuvwxyz', 10, '..'); // outputs abcd..wxyz
echo strShorten('abcdefghijklmnopqrstuvwxyz'); // outputs abc/.../yz

?>

<< Back to user notes page

To Top