Tuesday, May 12, 2009

Truncate Memo Field based on specified length, string truncated to nearest space or CrLf - PHP

function TruncateMemo($str, $ln)
{
if (strlen($str) > 0 && strlen($str) > $ln) {
$k = 0;
while ($k >= 0 && $k < strlen($str)) {
$i = strpos($str, " ", $k);
$j = strpos($str,chr(10), $k);
if ($i === false && $j === false) { // Not able to truncate
return $str;
} else {
// Get nearest space or CrLf
if ($i > 0 && $j > 0) {
if ($i < $j) {
$k = $i;
} else {
$k = $j;
}
} elseif ($i > 0) {
$k = $i;
} elseif ($j > 0) {
$k = $j;
}
// Get truncated text
if ($k >= $ln) {
return substr($str, 0, $k) . "...";
} else {
$k ++;
}
}
}
} else {
return $str;
}
}

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

No comments: