note 39018 deleted from function.substr by tomsommer
| From: | tomsommer@php.net | Date: | Wed, 14 Jan 2004 18:54:40 +0000 |
| Subject: | note 39018 deleted from function.substr by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-63545@lists.php.net to get a copy of this message | ||
Note Submitter: Thijs Wijnmaalen (thijs_nllinux.nl)
----
I wrote some code for people who have built a search-engine with PHP. The function makes it possible
to summarize each search result on a smarter way than te normal substr() function.
<?php
function substr_index($text, $maxChars = 20, $splitter
= '...') {
$theReturn = $text;
$lastSpace = false;
if (strlen($text) > $maxChars) {
$theReturn = substr($text, 0, $maxChars - 1);
if (in_array(substr($text, $maxChars - 1, 1),
array(' ', '.', '!', '?'))) {
$theReturn .= substr($text, $maxChars, 1);
} else {
$theReturn = substr($theReturn, 0, $maxChars -
strlen($splitter));
$lastSpace = strrpos($theReturn, ' ');
if ($lastSpace !== false) {
$theReturn = substr($theReturn, 0, $lastSpace);
}
if (in_array(substr($theReturn, -1, 1), array(','))) {
$theReturn = substr($theReturn, 0, -1);
}
$theReturn .= $splitter;
}
}
return $theReturn;
}
?>