note 118705 added to function.substr-replace
| From: | nospam at nospam dot com | Date: | Thu, 21 Jan 2016 21:45:39 +0000 |
| Subject: | note 118705 added to function.substr-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-204745@lists.php.net to get a copy of this message | ||
<?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
?>
----
Server IP: 72.52.91.14
Probable Submitter: 104.50.169.204
----
Manual Page -- http://php.net/manual/en/function.substr-replace.php
Edit -- https://master.php.net/note/edit/118705
Del: integrated -- https://master.php.net/note/delete/118705/integrated
Del: useless -- https://master.php.net/note/delete/118705/useless
Del: bad code -- https://master.php.net/note/delete/118705/bad+code
Del: spam -- https://master.php.net/note/delete/118705/spam
Del: non-english -- https://master.php.net/note/delete/118705/non-english
Del: in docs -- https://master.php.net/note/delete/118705/in+docs
Del: other reasons-- https://master.php.net/note/delete/118705
Reject -- https://master.php.net/note/reject/118705
Search -- https://master.php.net/manage/user-notes.php