]> git.mxchange.org Git - friendica.git/blob - vendor/smarty/smarty/libs/plugins/shared.mb_wordwrap.php
21632a1c014cd62f8e86a6b46a91cc040a6ecb5d
[friendica.git] / vendor / smarty / smarty / libs / plugins / shared.mb_wordwrap.php
1 <?php
2 /**
3  * Smarty shared plugin
4  *
5  * @package    Smarty
6  * @subpackage PluginsShared
7  */
8
9 if (!function_exists('smarty_mb_wordwrap')) {
10
11     /**
12      * Wrap a string to a given number of characters
13      *
14      * @link   http://php.net/manual/en/function.wordwrap.php for similarity
15      *
16      * @param  string  $str   the string to wrap
17      * @param  int     $width the width of the output
18      * @param  string  $break the character used to break the line
19      * @param  boolean $cut   ignored parameter, just for the sake of
20      *
21      * @return string  wrapped string
22      * @author Rodney Rehm
23      */
24     function smarty_mb_wordwrap($str, $width = 75, $break = "\n", $cut = false)
25     {
26         // break words into tokens using white space as a delimiter
27         $tokens =
28             preg_split('!(\s)!S' . Smarty::$_UTF8_MODIFIER, $str, - 1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
29         $length = 0;
30         $t = '';
31         $_previous = false;
32         $_space = false;
33
34         foreach ($tokens as $_token) {
35             $token_length = mb_strlen($_token, Smarty::$_CHARSET);
36             $_tokens = array($_token);
37             if ($token_length > $width) {
38                 if ($cut) {
39                     $_tokens = preg_split('!(.{' . $width . '})!S' . Smarty::$_UTF8_MODIFIER, $_token, - 1,
40                                           PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
41                 }
42             }
43
44             foreach ($_tokens as $token) {
45                 $_space = !!preg_match('!^\s$!S' . Smarty::$_UTF8_MODIFIER, $token);
46                 $token_length = mb_strlen($token, Smarty::$_CHARSET);
47                 $length += $token_length;
48
49                 if ($length > $width) {
50                     // remove space before inserted break
51                     if ($_previous) {
52                         $t = mb_substr($t, 0, - 1, Smarty::$_CHARSET);
53                     }
54
55                     if (!$_space) {
56                         // add the break before the token
57                         if (!empty($t)) {
58                             $t .= $break;
59                         }
60                         $length = $token_length;
61                     }
62                 } elseif ($token == "\n") {
63                     // hard break must reset counters
64                     $_previous = 0;
65                     $length = 0;
66                 }
67                 $_previous = $_space;
68                 // add the token
69                 $t .= $token;
70             }
71         }
72
73         return $t;
74     }
75 }