server/onyx/modules/templates/smarty/plugins/shared.mb_wordwrap.php

74 lines
2.4 KiB
PHP
Raw Normal View History

2013-10-09 13:40:23 +00:00
<?php
/**
* Smarty shared plugin
*
2015-01-14 10:28:47 +00:00
* @package Smarty
2013-10-09 13:40:23 +00:00
* @subpackage PluginsShared
*/
2013-10-09 17:08:38 +00:00
if (!function_exists('smarty_mb_wordwrap')) {
2013-10-09 13:40:23 +00:00
/**
* Wrap a string to a given number of characters
*
2015-01-14 10:28:47 +00:00
* @link http://php.net/manual/en/function.wordwrap.php for similarity
*
2013-10-09 17:08:38 +00:00
* @param string $str the string to wrap
* @param int $width the width of the output
* @param string $break the character used to break the line
* @param boolean $cut ignored parameter, just for the sake of
2015-01-14 10:28:47 +00:00
*
2013-10-09 17:08:38 +00:00
* @return string wrapped string
2013-10-09 13:40:23 +00:00
* @author Rodney Rehm
*/
2015-01-14 10:28:47 +00:00
function smarty_mb_wordwrap($str, $width = 75, $break = "\n", $cut = false)
2013-10-09 13:40:23 +00:00
{
// break words into tokens using white space as a delimiter
2015-01-14 10:28:47 +00:00
$tokens = preg_split('!(\s)!S' . Smarty::$_UTF8_MODIFIER, $str, - 1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
2013-10-09 13:40:23 +00:00
$length = 0;
$t = '';
$_previous = false;
2015-01-14 10:28:47 +00:00
$_space = false;
2013-10-09 13:40:23 +00:00
foreach ($tokens as $_token) {
$token_length = mb_strlen($_token, Smarty::$_CHARSET);
$_tokens = array($_token);
if ($token_length > $width) {
2015-01-14 10:28:47 +00:00
if ($cut) {
$_tokens = preg_split('!(.{' . $width . '})!S' . Smarty::$_UTF8_MODIFIER, $_token, - 1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
2013-10-09 13:40:23 +00:00
}
}
foreach ($_tokens as $token) {
$_space = !!preg_match('!^\s$!S' . Smarty::$_UTF8_MODIFIER, $token);
$token_length = mb_strlen($token, Smarty::$_CHARSET);
$length += $token_length;
if ($length > $width) {
// remove space before inserted break
2015-01-14 10:28:47 +00:00
if ($_previous) {
$t = mb_substr($t, 0, - 1, Smarty::$_CHARSET);
2013-10-09 13:40:23 +00:00
}
2015-01-14 10:28:47 +00:00
if (!$_space) {
// add the break before the token
if (!empty($t)) {
$t .= $break;
}
$length = $token_length;
2013-10-09 13:40:23 +00:00
}
2013-10-09 17:08:38 +00:00
} elseif ($token == "\n") {
2013-10-09 13:40:23 +00:00
// hard break must reset counters
$_previous = 0;
$length = 0;
}
2015-01-14 10:28:47 +00:00
$_previous = $_space;
2013-10-09 13:40:23 +00:00
// add the token
$t .= $token;
}
}
return $t;
}
}