6 * @subpackage PluginsModifier
10 * Smarty capitalize modifier plugin
12 * Name: capitalize<br>
13 * Purpose: capitalize words in the string
14 * {@internal {$string|capitalize:true:true} is the fastest option for MBString enabled systems }}
16 * @param string $string string to capitalize
17 * @param boolean $uc_digits also capitalize "x123" to "X123"
18 * @param boolean $lc_rest capitalize first letters, lowercase all following letters "aAa" to "Aaa"
20 * @return string capitalized string
21 * @author Monte Ohrt <monte at ohrt dot com>
24 function smarty_modifier_capitalize($string, $uc_digits = false, $lc_rest = false)
26 if (Smarty::$_MBSTRING) {
28 // uppercase (including hyphenated words)
29 $upper_string = mb_convert_case($string, MB_CASE_TITLE, Smarty::$_CHARSET);
31 // uppercase word breaks
32 $upper_string = preg_replace_callback("!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER,
33 'smarty_mod_cap_mbconvert_cb', $string);
35 // check uc_digits case
37 if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches,
38 PREG_OFFSET_CAPTURE)) {
39 foreach ($matches[ 1 ] as $match) {
41 substr_replace($upper_string, mb_strtolower($match[ 0 ], Smarty::$_CHARSET), $match[ 1 ],
47 preg_replace_callback("!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_mbconvert2_cb',
54 $string = strtolower($string);
56 // uppercase (including hyphenated words)
58 preg_replace_callback("!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_ucfirst_cb',
60 // check uc_digits case
62 if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches,
63 PREG_OFFSET_CAPTURE)) {
64 foreach ($matches[ 1 ] as $match) {
66 substr_replace($upper_string, strtolower($match[ 0 ]), $match[ 1 ], strlen($match[ 0 ]));
70 $upper_string = preg_replace_callback("!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_ucfirst2_cb',
77 * Bug: create_function() use exhausts memory when used in long loops
78 * Fix: use declared functions for callbacks instead of using create_function()
79 * Note: This can be fixed using anonymous functions instead, but that requires PHP >= 5.3
81 * @author Kyle Renfrow
83 function smarty_mod_cap_mbconvert_cb($matches)
85 return stripslashes($matches[ 1 ]) . mb_convert_case(stripslashes($matches[ 2 ]), MB_CASE_UPPER, Smarty::$_CHARSET);
88 function smarty_mod_cap_mbconvert2_cb($matches)
90 return stripslashes($matches[ 1 ]) . mb_convert_case(stripslashes($matches[ 3 ]), MB_CASE_UPPER, Smarty::$_CHARSET);
93 function smarty_mod_cap_ucfirst_cb($matches)
95 return stripslashes($matches[ 1 ]) . ucfirst(stripslashes($matches[ 2 ]));
98 function smarty_mod_cap_ucfirst2_cb($matches)
100 return stripslashes($matches[ 1 ]) . ucfirst(stripslashes($matches[ 3 ]));