RE: [SMARTY-DEV] A modifier in case someone needs it.
| From: | luis | Date: | Mon, 14 Apr 2003 14:23:43 +0000 |
| Subject: | RE: [SMARTY-DEV] A modifier in case someone needs it. | ||
| References: | 1 | Groups: | php.smarty.dev |
| Request: | Send a blank email to php-smarty-dev+get-1146@lists.php.net to get a copy of this message | ||
Yes, the example is wrong, should be
{$foo|adjust:20:"-":"..."}
Sorry :-)
-----Original Message-----
From: luis [mailto:luis@fuegolabs.com]
Sent: Monday, April 14, 2003 11:13 AM
To: 'Smarty Dev'
Subject: [SMARTY-DEV] A modifier in case someone needs it.
This is a modifier based in the truncate modifier, it can be used to
"adjust" the size of strings to some length, truncating
If necessary or padding if necessary.
Usage:
|adjust:length:padding:append_if_truncate:break_words
Example
{$foo|20:"-":"."}
Will adjust $foo to 30 characters adding "-" to pad the string if
needed. If the string
Is truncated "." is added at the end.
The default pad filler is " "
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* Type: modifier
* Name: adjust
* Purpose: Adjust a string to a certain length if necessary,
* optionally splitting in the middle of a word, and
* appending the $etc string or padding the string
* using $pad as filler.
* -------------------------------------------------------------
*/
function smarty_modifier_adjust($string, $length = 80,
$pad = ' ',
$etc = '...',
$break_words = false)
{
if ($length == 0)
return '';
if (strlen($string) > $length) {
$length -= strlen($etc);
$fragment = substr($string, 0, $length+1);
if ($break_words)
$fragment = substr($fragment, 0, -1);
else
$fragment = preg_replace('/\s+(\S+)?$/', '', $fragment);
return $fragment.$etc;
} elseif(strlen($string)<$length) {
return $string.str_repeat($pad,$length-strlen($string));
} else {
return $string;
}
}
?>