I'm not certain what you are trying to achieve, but some things seem odd/wrong.
Your regexp probably doesn't do what you want it to, since you are looking for the character 'S'
if(preg_match('#S#', $end_char))
Since this calculation includes unnecessary stuff, it's probably wrong, or at least it can be simplified
$chars += strpos($text, ' ', $chars) - $chars;
+= means add and assign, so the above is equivalent to
$chars = $chars + strpos($text, ' ', $chars) - $chars;
Which makes it obvious that you could just
$chars = strpos($text, ' ', $chars);
But if my guess is right, you want to cut at the last whitespace before the specified string length
function snippet($text, $chars, $dots = false)
{
$p = '#(.*)\s.*$#';
if ($chars < strlen($text))
$text = substr($text, 0, 80);
# Text is allready shorter than it is allowed to be. Everything is shown, so no need for ellipsis
else
return $text;
# Get all text up to before the last white space.
if (preg_match($p, $text, $m)) {
$m = $m[1];
if (in_array($m[strlen($m)-1], array(',',';','.')))
$m = substr($m, 0, strlen($m) - 1);
return $dots ? $m . '…' : $m;
}
return $dots ? $text . '…' : $text;
}
$s = 'Some text that should be cut, ending in ellipsis. Some text that should be cut, ending in ellipsis.';
echo snippet($s, 80, true) . '<br/>';
echo snippet($s, 80, false) . '<br/>';
echo snippet($s, 400, true) . '<br/>';
echo snippet($s, 400, false) . '<br/>';
Style may vary from language to language or country to country, but from a typographical point of view you should use the ellipsis character instead of three dots.
On another point, you should not use the deprecated <font> element, but rather use CSS to control layout.
<span style="color: red">Please enter a keyword</span>
or
<style type="text/css">
.highlightRed { color: red; }
</style>
<span class="highlightRed">Please enter a keyword</span>