21
A few missing PHP functions
Not that these are any invention of mine, but I’ve kind of gathered them and made them a default on most of my projects.
Feel free to use them as you wish.
The first three or kind of self-explanatory
function right($value, $count) {
return substr($value, ($count*-1));
}
function mid($string, $start, $count) {
return substr($string, $start, $count);
}
function left($string, $count) {
return substr($string, 0, $count);
}
The excerpt() function is very useful when you need to take the first X number of characters from an input.
function excerpt($input, $length, $trailing='...', $trail = true, $strip = true) {
if ($strip) {
$input = strip_tags($input);
}
if (strlen($input) <= $length) {
return strip_tags($input);
}
$last_space = strrpos(substr($input, 0, $length), ' ');
$trimmed_text = substr($input, 0, $last_space);
if ($trail) {
$trimmed_text .= $trailing;
}
return $trimmed_text;
}
The required inputs are $input and $length, but $trailing, $trail and $strip have default values and are therefore optional. The default trailing is ‘…’, and both $trail and $strip are true by default.
The function first strips the $input and checks it’s length. If it exceeds the maximum desired length ($length), than we will cut the $input at it’s last space (so we won’t cut through a word) and,if $trail is true, add $trailing to the end.
Example of simple usage:
$news="This is a long news story which I would like to excerpt the first 20 characters from."; print excerpt($news,'20');
Would return: “This is a long news …”
Feel free to play around with these functions, and please post your ideas or comments here for all to benefit.












