note 74763 deleted from function.strpos by levim
| From: | levim@php.net | Date: | Tue, 22 Jul 2014 03:29:01 +0000 |
| Subject: | note 74763 deleted from function.strpos by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-200016@lists.php.net to get a copy of this message | ||
Note Submitter: Rich Deeson
----
Here's a somewhat more efficient way to truncate a string at the end of a word. This will end
the string on the last dot or last space, whichever is closer to the cut off point. In some cases, a
full stop may not be followed by a space eg when followed by a HTML tag.
<?php
$shortstring = substr($originalstring, 0, 400);
$lastdot = strrpos($shortstring, ".");
$lastspace = strrpos($shortstring, " ");
$shortstring = substr($shortstring, 0, ($lastdot > $lastspace? $lastdot : $lastspace));
?>
Obviously, if you only want to split on a space, you can simplify this:
<?php
$shortstring = substr($originalstring, 0, 400);
$shortstring = substr($shortstring, 0, strrpos($shortstring, " "));
?>