Merge pull request #15338 from totten/master-poc-postcommit
[civicrm-core.git] / CRM / Core / Smarty / plugins / modifier.mb_truncate.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 * $Id$
17 *
18 */
19
20 /**
21 * Smarty plugin
22 * @package Smarty
23 * @subpackage plugins
24 */
25
26 /**
27 * Smarty mb_truncate modifier plugin
28 *
29 * Type: modifier<br>
30 * Name: mb_truncate<br>
31 * Purpose: Truncate a string to a certain length if necessary,
32 * optionally splitting in the middle of a word, and
33 * appending the $etc string. Multibyte version.
34 * @link http://smarty.php.net/manual/en/language.modifier.truncate.php
35 * truncate (Smarty online manual)
36 *
37 * @param string $string
38 * @param int $length
39 * @param string $etc
40 * @param bool $break_words
41 *
42 * @return string
43 */
44 function smarty_modifier_mb_truncate($string, $length = 80, $etc = '...',
45 $break_words = FALSE
46 ) {
47 if (function_exists('mb_internal_encoding') and function_exists('mb_strlen') and function_exists('mb_substr')) {
48 mb_internal_encoding('UTF-8');
49 $strlen = 'mb_strlen';
50 $substr = 'mb_substr';
51 }
52 else {
53 $strlen = 'strlen';
54 $substr = 'substr';
55 }
56
57 if ($length == 0) {
58
59 return '';
60
61 }
62
63 if ($strlen($string) > $length) {
64 $length -= $strlen($etc);
65 if (!$break_words) {
66 $string = preg_replace('/\s+?(\S+)?$/', '', $substr($string, 0, $length + 1));
67 }
68
69 return $substr($string, 0, $length) . $etc;
70 }
71 else {
72 return $string;
73 }
74 }
75
76 /* vim: set expandtab: */