/**
 * modifier plugin :  Truncate a string
 *
 * Truncate a string to a certain length if necessary, optionally splitting in
 * the middle of a word, and appending the $etc string.
 * <pre>{$mytext|truncate}
 * {$mytext|truncate:40}
 * {$mytext|truncate:45:'...'}
 * {$mytext|truncate:60:'...':true}
 * </pre>
 * @param string $string the string to truncate
 * @param integer $length the number of char to keep
 * @param string $etc the string to append to the truncated string
 * @param boolean $break_words false if the last word shouldn't be cut
 * @return string
 */
function jtpl_modifier_common_truncate($string, $length = 80, $etc = '...', $break_words = false)
{
    if (function_exists('mb_strlen')) {
        $f_strlen = 'mb_strlen';
    } else {
        $f_strlen = 'iconv_strlen';
    }
    if (function_exists('mb_substr')) {
        $f_substr = 'mb_substr';
    } else {
        $f_substr = 'iconv_substr';
    }
    if ($length == 0) {
        return '';
    }
    $charset = jTpl::getEncoding();
    if ($f_strlen($string, $charset) > $length) {
        $length -= $f_strlen($etc, $charset);
        if (!$break_words) {
            $string = preg_replace('/\\s+?(\\S+)?$/', '', $f_substr($string, 0, $length + 1, $charset));
        }
        return $f_substr($string, 0, $length, $charset) . $etc;
    } else {
        return $string;
    }
}
/**
 * Plugin from smarty project and adapted for jtpl
 * @package    jelix
 * @subpackage jtpl_plugin
 * @copyright  2001-2003 ispi of Lincoln, Inc.
 * @link http://smarty.php.net/
 * @link http://jelix.org/
 * @licence    GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html
 */
function jtpl_modifier_common_regex_replace($string, $search, $replace)
{
    if (preg_match('!\\W(\\w+)$!s', $search, $match) && strpos($match[1], 'e') !== false) {
        $search = substr($search, 0, -iconv_strlen($match[1], jTpl::getEncoding())) . str_replace('e', '', $match[1]);
    }
    return preg_replace($search, $replace, $string);
}
/**
 * Modifier plugin : count the number of characters in a text
 *
 * <pre>{$mytext|count_characters}
 * {$mytext|count_characters:true}</pre>
 * @param string $string
 * @param boolean $include_spaces include whitespace in the character count
 * @return integer
 */
function jtpl_modifier_common_count_characters($string, $include_spaces = false)
{
    if ($include_spaces) {
        return iconv_strlen($string, jTpl::getEncoding());
    }
    return preg_match_all("/[^\\s]/", $string, $match);
}