Exemple #1
0
 /**
  * Limit the number of characters in a string.
  *
  * @param string $value
  * @param int    $limit
  * @param string $end
  *
  * @return string
  */
 public static function limit(string $value, int $limit = 100, string $end = '...') : string
 {
     if (mb_strwidth($value, 'UTF-8') <= $limit) {
         return $value;
     }
     return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')) . $end;
 }
function spa_display_member_roll($members, $text1, $text2)
{
    $out = '';
    $cap = '';
    $first = true;
    $out .= '<fieldset class="sfsubfieldset">';
    $out .= '<legend>' . $text1 . '</legend>';
    if ($members) {
        $out .= '<p><b>' . count($members) . ' ' . spa_text('member(s) in this user group') . '</b></p>';
        for ($x = 0; $x < count($members); $x++) {
            if (strncasecmp($members[$x]->display_name, $cap, 1) != 0) {
                if (!$first) {
                    $out .= '</ul>';
                }
                $cap = substr($members[$x]->display_name, 0, 2);
                if (function_exists('mb_strwidth')) {
                    if (mb_strwidth($cap) == 2) {
                        $cap = substr($cap, 0, 1);
                    }
                } else {
                    $cap = substr($cap, 0, 1);
                }
                $out .= '<p style="clear:both;"></p><hr /><h4>' . strtoupper($cap) . '</h4>';
                $out .= '<ul class="memberlist">';
                $first = false;
            }
            $out .= '<li>' . sp_filter_name_display($members[$x]->display_name) . '</li>';
        }
        $out .= '</ul>';
    } else {
        $out .= $text2;
    }
    $out .= '</fieldset>';
    return $out;
}
/**
 * Smarty truncate for cn modifier plugin
 *
 * Type:     modifier<br>
 * Name:     truncate<br>
 * Purpose:  Truncate a string to a certain length if necessary,
 *           optionally splitting in the middle of a word, and
 *           appending the $etc string or inserting $etc into the middle.
 * @link http://smarty.php.net/manual/en/language.modifier.truncate.php
 *          truncate (Smarty online manual)
 * @author   Monte Ohrt <monte at ohrt dot com>
 * @param string
 * @param integer
 * @param string
 * @param boolean
 * @param boolean
 * @return string
 */
function smarty_modifier_truncate_cn($string, $length = 80, $charset = 'UTF-8', $etc = '...')
{
    if (mb_strwidth($string, 'UTF-8') < $length) {
        return $string;
    }
    return mb_strimwidth($string, 0, $length, '', $charset) . $etc;
}
 function str_limit($value, $limit = 100, $end = '...')
 {
     if (mb_strwidth($value, 'UTF-8') <= $limit) {
         return $value;
     }
     return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')) . $end;
 }
Exemple #5
0
function cut($str)
{
    if (mb_strwidth($str, 'UTF-8') > 30) {
        $i = mb_strlen($str, 'UTF-8') % 2 ? (mb_strlen($str, 'UTF-8') + 1) / 2 : mb_strlen($str, 'UTF-8') / 2;
        do {
            $k = mb_strwidth(mb_substr($str, 0, $i, 'UTF-8'), 'UTF-8') - mb_strwidth(mb_substr($str, $i, 30, 'UTF-8'), 'UTF-8');
            echo "k={$k}, <br />";
            if ($k > 1) {
                --$i;
            } elseif ($k < 1 && $k != 0) {
                ++$i;
            }
        } while (abs($k) > 2);
        while (preg_match("/^[a-zA-Z\\s]+\$/", mb_substr($str, $i, 1, 'UTF-8'))) {
            ++$i;
        }
        if (strpos(mb_substr($str, $i - 2, 4, 'UTF-8'), " ")) {
            if (mb_substr($str, $i, 1, 'UTF-8') == ' ') {
                $str2 = mb_substr($str, $i + 1, 30, 'UTF-8');
                return str_replace(" {$str2}", "}\\underBlank{" . $str2, $str);
            } elseif (mb_substr($str, $i - 1, 1, 'UTF-8') == ' ') {
                $str2 = mb_substr($str, $i, 30, 'UTF-8');
                return str_replace(" {$str2}", "}\\underBlank{" . $str2, $str);
            } elseif (mb_substr($str, $i + 1, 1, 'UTF-8') == ' ') {
                $str2 = mb_substr($str, $i + 2, 30, 'UTF-8');
                return str_replace(" {$str2}", "}\\underBlank{" . $str2, $str);
            }
        }
        $str2 = mb_substr($str, $i, 30, 'UTF-8');
        return str_replace($str2, "}\\underBlank{" . $str2, $str);
    }
    return $str;
}
Exemple #6
0
 /**
  * Normalizes a single name item
  * @param string $strNameItem
  * @return string
  */
 public static function NormalizeNameItem($strNameItem)
 {
     $strNameItem = trim($strNameItem);
     if (!mb_strlen($strNameItem)) {
         return null;
     }
     $strNameItem = mb_strtolower($strNameItem);
     $strFinal = '';
     $intLength = mb_strlen($strNameItem);
     for ($i = 0; $i < $intLength; $i++) {
         $strCurrent = mb_substr($strNameItem, $i, 1);
         foreach (self::$Internationalized as $strNormalized => $strInternationalized) {
             if (mb_strpos($strInternationalized, $strCurrent) !== false) {
                 $strCurrent = $strNormalized;
             }
         }
         if (mb_strwidth($strCurrent) == 1) {
             $intOrd = ord($strCurrent);
             if ($intOrd >= ord('a') && $intOrd <= ord('z')) {
                 $strFinal .= $strCurrent;
             }
         }
     }
     return $strFinal;
 }
 function execute($requests)
 {
     $u = $GLOBALS['AUTH']->uid();
     // --- リクエスト変数
     $subject = $requests['subject'];
     $body = $requests['body'];
     $public_flag = util_cast_public_flag_diary($requests['public_flag']);
     $category = $requests['category'];
     $is_comment_input = $requests['is_comment_input'];
     // ----------
     $sessid = session_id();
     t_image_clear_tmp($sessid);
     $upfiles = array(1 => $_FILES['upfile_1'], $_FILES['upfile_2'], $_FILES['upfile_3']);
     $tmpfiles = array(1 => '', '', '');
     $filesize = 0;
     foreach ($upfiles as $key => $upfile) {
         if (!empty($upfile) && $upfile['error'] !== UPLOAD_ERR_NO_FILE) {
             if (!($image = t_check_image($upfile))) {
                 $_REQUEST['msg'] = '画像は' . IMAGE_MAX_FILESIZE . 'KB以内のGIF・JPEG・PNGにしてください';
                 openpne_forward('pc', 'page', 'h_diary_add');
                 exit;
             } else {
                 $filesize += $image['size'];
                 $tmpfiles[$key] = t_image_save2tmp($upfile, $sessid, "d_{$key}", $image['format']);
             }
         }
     }
     $category_list = array_unique(preg_split('/\\s+/', $category));
     if (count($category_list) > 5) {
         $_REQUEST['msg'] = 'カテゴリは5つまでしか指定できません';
         openpne_forward('pc', 'page', 'h_diary_add');
         exit;
     }
     foreach ($category_list as $value) {
         if (mb_strwidth($value) > 20) {
             $_REQUEST['msg'] = 'カテゴリはひとつにつき全角10文字(半角20文字)以内で入力してください';
             openpne_forward('pc', 'page', 'h_diary_add');
             exit;
         }
     }
     // 画像アップロード可能サイズチェック
     if ($filesize) {
         $result = util_image_check_add_image_upload($filesize, $u, 'diary');
         if ($result) {
             if ($result == 2) {
                 $result = 3;
             }
             $msg = util_image_get_upload_err_msg($result);
             $_REQUEST['msg'] = $msg;
             openpne_forward('pc', 'page', 'h_diary_add');
             exit;
         }
     }
     $this->set('inc_navi', fetch_inc_navi('h'));
     //プロフィール
     $this->set("member", db_member_c_member4c_member_id($u));
     $form_val = array("subject" => $subject, "body" => $body, "public_flag" => $public_flag, "upfile_1" => $_FILES['upfile_1'], "upfile_2" => $_FILES['upfile_2'], "upfile_3" => $_FILES['upfile_3'], "tmpfile_1" => $tmpfiles[1], "tmpfile_2" => $tmpfiles[2], "tmpfile_3" => $tmpfiles[3], "category" => join(" ", $category_list), "is_comment_input" => $is_comment_input);
     $this->set("form_val", $form_val);
     return 'success';
 }
Exemple #8
0
 /**
  * Returns the length of a string, using mb_strwidth if it is available.
  *
  * @param string $string The string to check its length
  *
  * @return int The length of the string
  */
 public static function strlen($string)
 {
     if (false === ($encoding = mb_detect_encoding($string, null, true))) {
         return strlen($string);
     }
     return mb_strwidth($string, $encoding);
 }
Exemple #9
0
/**
 * 字符串截取,支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = false)
{
    if (function_exists("mb_strimwidth")) {
        $slice = mb_strimwidth($str, $start, $length, '', $charset);
        // mb_strimwidth 截取字符串 中文算2个字节,英文算1个
    } elseif (function_exists('mb_substr')) {
        $slice = mb_substr($str, $start, $length, $charset);
    } elseif (function_exists("iconv_substr")) {
        $slice = iconv_substr($str, $start, $length, $charset);
    } else {
        $re['utf-8'] = "/[-]|[�-�][�-�]|[�-�][�-�]{2}|[�-�][�-�]{3}/";
        $re['gb2312'] = "/[-]|[�-�][�-�]/";
        $re['gbk'] = "/[-]|[�-�][@-�]/";
        $re['big5'] = "/[-]|[�-�]([@-~]|�-�])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
    }
    if ($suffix) {
        return mb_strwidth($slice, $charset) > $length ? $slice : $slice . '...';
        // mb_strwidth 计算字符串长度 中文算2个字节,英文算1个
    } else {
        return $slice;
    }
    //    return $suffix ? $slice.'...' : $slice;
}
/**
 * Compact a string to a maximum length
 *
 * @access public
 * @param string $str String to compact
 * @param integer $length Length to trim at
 * @return string Compact string; otherwise, original string
 */
function stringCompact($str, $length = 0)
{
    // mb_strwidth is better than using mb_strlen. See PHP docs for more details
    if ($length === 0 || mb_strwidth($str) <= $length) {
        return $str;
    }
    return mb_strimwidth($str, 0, $length, '...');
}
Exemple #11
0
 /**
  * get substr support chinese
  * return $str
  */
 static function getSubStr($str, $length, $postfix = '...', $encoding = 'UTF-8')
 {
     $realLen = mb_strwidth($str, $encoding);
     if (!is_numeric($length) or $length * 2 >= $realLen) {
         return htmlspecialchars($str, ENT_QUOTES, $encoding);
     }
     $str = mb_strimwidth($str, 0, $length * 2, $postfix, $encoding);
     return htmlspecialchars($str, ENT_QUOTES, $encoding);
 }
Exemple #12
0
 /**
  *
  * @param $attribute
  * @param $value
  * @param $parameters
  * @return bool
  */
 public function validateHasMultiByte($attribute, $value, $parameters)
 {
     $len = mb_strlen($value, 'UTF-8');
     $wdt = mb_strwidth($value, 'UTF-8');
     if (20 < $wdt - $len) {
         return true;
     }
     return false;
 }
Exemple #13
0
 public static function znStrLength($str, $min, $max = 999999)
 {
     $length = mb_strwidth($str);
     if ($length >= $min && $length <= $max) {
         return true;
     } else {
         return false;
     }
 }
Exemple #14
0
 /**
  * Returns the length of a string, using mb_strwidth if it is available.
  *
  * @param string $string The string to check its length
  *
  * @return int The length of the string
  */
 public static function strlen($string)
 {
     if (!function_exists('mb_strwidth')) {
         return strlen($string);
     }
     if (false === ($encoding = mb_detect_encoding($string))) {
         return strlen($string);
     }
     return mb_strwidth($string, $encoding);
 }
Exemple #15
0
 /**
  * 裁剪字符串,加“...”
  */
 static function substr($str, $length, $endfix = '...')
 {
     mb_internal_encoding("UTF-8");
     $str_length = mb_strwidth($str);
     if ($str_length > $length * 2) {
         return mb_substr($str, 0, $length) . $endfix;
     } else {
         return $str;
     }
 }
Exemple #16
0
 /**
  * Returns the length of a string, using mb_strwidth if it is available.
  *
  * @param string $string The string to check its length
  *
  * @return int The length of the string
  */
 protected function strlen($string)
 {
     if (!function_exists('mb_strwidth')) {
         return strlen($string);
     }
     if (false === ($encoding = mb_detect_encoding($string, null, true))) {
         return strlen($string);
     }
     return mb_strwidth($string, $encoding);
 }
Exemple #17
0
function string_cut($String, $Length, $Title = 0, $Dots = 1)
{
    if (!$Length) {
        return $String;
    }
    if (!function_exists('mb_substr')) {
        return strlen($String) > $Length + 3 || !$Dots ? $Title ? '<span title="' . htmlspecialchars($String) . '">' . htmlspecialchars(substr_replace($String, $Dots ? '...' : '', $Length)) . '</span>' : htmlspecialchars(substr_replace($String, $Dots ? '...' : '', $Length)) : htmlspecialchars($String);
    } else {
        return mb_strwidth($String, 'UTF-8') > $Length + 3 || !$Dots ? $Title ? '<span title="' . htmlspecialchars($String) . '">' . htmlspecialchars(mb_substr($String, 0, $Length, 'UTF-8')) . ($Dots ? '...' : '') . '</span>' : htmlspecialchars(mb_substr($String, 0, $Length, 'UTF-8')) . ($Dots ? '...' : '') : htmlspecialchars($String);
    }
}
Exemple #18
0
 function execute($requests)
 {
     $errors = array();
     if (!db_common_is_mailaddress($requests['pc_address']) || is_ktai_mail_address($requests['pc_address'])) {
         $errors[] = 'PCメールアドレスを正しく入力してください';
     }
     if (OPENPNE_AUTH_MODE == 'email') {
         if ($requests['password'] !== $requests['password2']) {
             $errors[] = 'パスワードが一致していません';
         }
     }
     if ($requests['admin_password'] !== $requests['admin_password2']) {
         $errors[] = '管理用パスワードが一致していません';
     }
     if (OPENPNE_AUTH_MODE == 'slavepne') {
         $auth_config = get_auth_config(false);
         $storage = Auth::_factory($auth_config['storage'], $auth_config['options']);
         $result = $storage->fetchData($requests['username'], $requests['password'], false);
         if ($result !== true) {
             $errors[] = 'ログインIDまたはパスワードが一致しません';
         }
     }
     if (OPENPNE_AUTH_MODE == 'pneid') {
         if (is_null($requests['username']) || $requests['username'] === '') {
             $errors[] = 'ログインIDを入力してください';
         } elseif (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9\\-_]+[a-zA-Z0-9]$/i', $requests['username'])) {
             $errors[] = 'ログインIDは4~30文字の半角英数字、記号(アンダーバー「_」、ハイフン「-」)で入力してください';
         } elseif (mb_strwidth($requests['username'], 'UTF-8') < 4) {
             $errors[] = "ログインIDは半角4文字以上で入力してください";
         } elseif (mb_strwidth($requests['username'], 'UTF-8') > 30) {
             $errors[] = "ログインIDは半角30文字以内で入力してください";
         }
     }
     if ($errors) {
         $this->handleError($errors);
     }
     // c_admin_config: SNS_NAME
     $data = array('name' => 'SNS_NAME', 'value' => $requests['SNS_NAME']);
     db_insert('c_admin_config', $data);
     // c_member_secure
     $data = array('c_member_id' => 1, 'hashed_password' => md5($requests['password']), 'hashed_password_query_answer' => '', 'pc_address' => t_encrypt($requests['pc_address']), 'ktai_address' => '', 'regist_address' => t_encrypt($requests['pc_address']), 'easy_access_id' => '');
     if (OPENPNE_AUTH_MODE == 'slavepne' && !IS_SLAVEPNE_EMAIL_REGIST) {
         $data['ktai_address'] = t_encrypt('*****@*****.**');
     }
     db_insert('c_member_secure', $data);
     // c_admin_user
     $data = array('username' => $requests['admin_username'], 'password' => md5($requests['admin_password']), 'auth_type' => 'all');
     db_insert('c_admin_user', $data);
     if (OPENPNE_AUTH_MODE != 'email') {
         db_member_insert_username(1, $requests['username']);
     }
     openpne_redirect('setup', 'page_setup_done');
 }
Exemple #19
0
 /**
  * @param $fontSize
  * @param int $w
  * @param int $h
  * @param string $txt
  * @param int $border
  * @param int $ln
  * @param string $align
  * @param bool $fill
  * @param string $link
  * @param int $stretch
  * @param bool $ignore_min_height
  * @param string $calign
  * @param string $valign
  */
 public function Cell_AutoFontSize($fontSize, $w = 0, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '', $stretch = 0, $ignore_min_height = false, $calign = 'T', $valign = 'M')
 {
     // 幅によってフォントサイズを6段階で縮小する。
     $size = $fontSize;
     for ($i = 0; $size > 0; $i++) {
         //if ( $w >= ( mb_strlen(trim($txt),'UTF-8')) * ($fontSize - $i) * 0.35 ) {
         if ($w >= mb_strwidth(trim($txt), 'UTF-8') * ($fontSize - $i) * 0.228) {
             break;
         }
         $size = $fontSize - $i;
     }
     $this->SetFontSize($size);
     $this->Cell($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
 }
Exemple #20
0
 /**
  * Output a row.
  *
  * @param array $row The row to output.
  * @param array $widths The widths of each column to output.
  * @param array $options Options to be passed.
  * @return void
  */
 protected function _render(array $row, $widths, $options = [])
 {
     if (count($row) === 0) {
         return;
     }
     $out = '';
     foreach ($row as $i => $column) {
         $pad = $widths[$i] - mb_strwidth($column);
         if (!empty($options['style'])) {
             $column = $this->_addStyle($column, $options['style']);
         }
         $out .= '| ' . $column . str_repeat(' ', $pad) . ' ';
     }
     $out .= '|';
     $this->_io->out($out);
 }
Exemple #21
0
 public function toString($line_sep = "\n", $space = " ", $col_sep = " : ", $col_end = "")
 {
     $rows = [];
     $max_line = [];
     foreach ($this->_lines as $k => $v) {
         $max_line[$k] = 0;
         $row = [];
         foreach ($v as $kk => $vv) {
             if ($max_line[$k] < count($vv)) {
                 $max_line[$k] = count($vv);
             }
             foreach ($vv as $kkk => $vvv) {
                 $max = $this->_max[$kk];
                 $len = mb_strwidth($vvv);
                 $row[$kk][$kkk] = $vvv . str_repeat($space, $max - $len);
             }
         }
         $rows[] = $row;
     }
     $lines = [];
     foreach ($rows as $k => $row) {
         $line = '';
         for ($i = 0; $i < $max_line[$k]; $i++) {
             for ($ii = 0; $ii < count($row); $ii++) {
                 if (isset($row[$ii][$i])) {
                     $line .= $row[$ii][$i];
                 } else {
                     $line .= str_repeat($space, $this->_max[$ii]);
                 }
                 if ($ii !== count($row) - 1) {
                     $line .= $col_sep;
                 } else {
                     $line .= $col_end;
                 }
             }
             $line .= $line_sep;
         }
         foreach ($this->_max as $v) {
             $line .= str_repeat('-', $v);
         }
         $line .= str_repeat('-', mb_strwidth($col_sep) * (count($this->_max) - 1));
         $line .= $line_sep;
         $lines[] = $line;
     }
     return implode("", $lines);
 }
 /**
  * 辞書自体のタイトルと説明文を直列化します。Shift_JISに存在しない符号位置が含まれているタイトル、または説明文は存在しないものとして扱います。
  * @param Dictionary $dictionary
  * @param string $lineCommentString 行コメント文字。
  * @param string[]|null $brackets 開き括弧と閉じ括弧の配列。指定されていればタイトルをこの括弧で囲み、タイトル先頭の行コメント文字を省略します。
  * @return string 改行はCRLFを使用します。辞書にタイトルか説明文のいずれかが存在すれば、末尾に改行を2つ付けます。どちらも無ければ空文字列を返します。
  */
 protected function serializeMetadata(Dictionary $dictionary, string $lineCommentString = '//', array $brackets = null) : string
 {
     $metadata = $dictionary->getMetadata();
     if (isset($metadata['@title'])) {
         $shiftJisableTitle = $this->convertToShiftJISable($metadata['@title']);
         if ($this->isShiftJISable($shiftJisableTitle)) {
             $prefix = ($brackets ? '' : "{$lineCommentString} ") . ($brackets[0] ?? self::DEFAULT_BRACKETS[0]);
             $serialized[] = $prefix . str_replace("\n", "\r\n{$lineCommentString} " . str_repeat(' ', max(0, mb_strwidth($prefix) - mb_strwidth("{$lineCommentString} "))), $shiftJisableTitle) . ($brackets[1] ?? self::DEFAULT_BRACKETS[1]);
         }
     }
     if (isset($metadata['@summary'])) {
         $shiftJisableSummary = $this->convertToShiftJISable($metadata['@summary']['lml']);
         if ($this->isShiftJISable($shiftJisableSummary)) {
             $serialized[] = "{$lineCommentString} " . str_replace("\n", "\r\n{$lineCommentString} ", $shiftJisableSummary);
         }
     }
     return isset($serialized) ? implode("\r\n", $serialized) . "\r\n\r\n" : '';
 }
Exemple #23
0
 /**
  * 通过DOM截取导语
  * 
  * @param \DOMNodeList $nodes         要处理的DOM节点
  * @param number       $limit_width   限制取多少宽度
  * @param number       $content_width 当前计算到达到多少宽度
  * 
  * @return array                      要删除的DOM节点
  */
 protected static function _truncateSummaryDom(\DOMNodeList $nodes, $limit_width, &$content_width = 0)
 {
     $will_remove_nodes = array();
     foreach ($nodes as $node) {
         //超长移除节点
         if ($content_width > $limit_width) {
             $will_remove_nodes[] = $node;
         }
         if ($node instanceof \DOMText) {
             //到达文本节点,计算字数
             $content_width += mb_strwidth($node->textContent);
         } elseif ($node->hasChildNodes()) {
             //非文本节点,继续遍历
             $will_remove_nodes = array_merge($will_remove_nodes, self::_truncateSummaryDom($node->childNodes, $limit_width, $content_width));
         }
     }
     return $will_remove_nodes;
 }
function smarty_modifier_t_truncate_callback($string, $width, $etc = '')
{
    // 入力文字列の幅が大きい場合は切り取り
    if (mb_strwidth($string) > $width) {
        $width = $width - mb_strwidth($etc);
        // 絵文字対応
        $offset = 0;
        $tmp_string = $string;
        while (preg_match('/\\[[ies]:[0-9]{1,3}\\]/', $tmp_string, $matches, PREG_OFFSET_CAPTURE)) {
            $emoji_str = $matches[0][0];
            $emoji_pos = $matches[0][1] + $offset;
            $emoji_len = strlen($emoji_str);
            $emoji_width = $emoji_len;
            // ASCIIなのでstrlenでOK
            // 絵文字直前までの文字列の幅
            $substr_width = mb_strwidth(substr($string, 0, $emoji_pos));
            // 絵文字がwidth位置より後ろ
            if ($substr_width >= $width) {
                break;
            }
            // 絵文字分を足してちょうどwidthと等しい
            if ($substr_width + 2 == $width) {
                $width = $substr_width + $emoji_width;
                break;
            }
            // 絵文字分を足すとwidthより大きい
            if ($substr_width + 2 > $width) {
                $width = $substr_width;
                break;
            }
            // 絵文字分を足してもwidthより小さい
            $offset = $emoji_pos + $emoji_len;
            $width = $width + $emoji_width - 2;
            $tmp_string = substr($string, $offset);
        }
        $string = mb_strimwidth($string, 0, $width) . $etc;
    }
    return $string;
}
function create_short_title($title_short, $length)
{
    $ls_search = array("&quot;", "&#34;", "&#x22;", "&lt;", "&#60;", "&#x3C;", "&gt;", "&#62;", "&#x3E;", "&#8211;", "&amp;", "&#38;", "&#x26;");
    //	&
    $ls_replace = array('"', '"', '"', '<', '<', '<', '>', '>', '>', "-", '&', '&', '&');
    //	&amp;"
    $ls_research = array('&', '"', "&#8211; ", '<', '>');
    //	&gt;"
    $ls_rereplace = array("&amp;", "&#8211; ", "&quot;", "&lt;", "&gt;");
    //	>
    $new_title = str_replace($ls_search, $ls_replace, $title_short);
    $len = mb_strwidth($new_title);
    // バイト数を調べる
    if ($len > $length) {
        //
        $title_short = mb_strimwidth($new_title, 0, $length, "...");
        $new_title_short = $title_short;
    } else {
        $new_title_short = $new_title;
    }
    $short_title = str_replace($ls_research, $ls_rereplace, $new_title_short);
    return $short_title;
}
Exemple #26
0
/**
 * Smarty truncate modifier plugin
 *
 * Type:     modifier<br>
 * Name:     truncate<br>
 * Purpose:  Truncate a string to a certain length if necessary,
 *           optionally splitting in the middle of a word, and
 *           appending the $etc string or inserting $etc into the middle.
 * @link http://smarty.php.net/manual/en/language.modifier.truncate.php
 *          truncate (Smarty online manual)
 * @author   Monte Ohrt <monte at ohrt dot com>
 * @param string
 * @param integer
 * @param string
 * @param boolean
 * @param boolean
 * @return string
 */
function smarty_modifier_cut($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
    if ($length == 0) {
        return '';
    }
    if (strlen($string) > $length) {
        if (function_exists(mb_strwidth)) {
            $length -= min($length, mb_strwidth($etc, 'UTF8'));
        } else {
            $length -= min($length, strlen($etc));
        }
        if (!$break_words && !$middle) {
            $string = utftrim(substr($string, 0, $length + 1));
            //            $string = preg_replace('/\s+?(\S+)?$/', '', utftrim(substr($string, 0, $length+1)));
        }
        if (!$middle) {
            return utftrim(substr($string, 0, $length)) . $etc;
        } else {
            return utftrim(substr($string, 0, $length / 2)) . $etc . utftrim(substr($string, -$length / 2));
        }
    } else {
        return $string;
    }
}
function mb_str_pad($mbstring, $pad_length, $pad_sbstring = ' ', $pad_type = STR_PAD_RIGHT, $encoding = null)
{
    $strwidth = func_num_args() < 5 ? mb_strwidth($mbstring) : mb_strwidth($mbstring, $encoding);
    $pad_length += strlen(bin2hex($mbstring)) / 2 - $strwidth;
    return str_pad($mbstring, $pad_length, $pad_sbstring, $pad_type);
}
Exemple #28
0
/**
 * String length wrapper. Uses mb_strwidth when available. Fallback to strlen.
 *
 * @param string $str
 * @return int String length
 */
function getStringLength($str)
{
    if (function_exists('mb_strwidth')) {
        return mb_strwidth($str, 'UTF-8');
    } else {
        return strlen($str);
    }
}
 private function splitStringByWidth($string, $width)
 {
     // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
     // additionally, array_slice() is not enough as some character has doubled width.
     // we need a function to split string not by character count but by string width
     if (!function_exists('mb_strwidth')) {
         return str_split($string, $width);
     }
     if (false === ($encoding = mb_detect_encoding($string))) {
         return str_split($string, $width);
     }
     $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
     $lines = array();
     $line = '';
     foreach (preg_split('//u', $utf8String) as $char) {
         // test if $char could be appended to current line
         if (mb_strwidth($line . $char, 'utf8') <= $width) {
             $line .= $char;
             continue;
         }
         // if not, push current line to array and make new line
         $lines[] = str_pad($line, $width);
         $line = $char;
     }
     if (strlen($line)) {
         $lines[] = count($lines) ? str_pad($line, $width) : $line;
     }
     mb_convert_variables($encoding, 'utf8', $lines);
     return $lines;
 }
 static function lengthAsEm($str)
 {
     if (function_exists('mb_strwidth')) {
         return mb_strwidth($str, 'utf-8');
     }
     $len = strlen($str);
     for ($i = $length = 0; $i < $len;) {
         $high = ord($str[$i]);
         if ($high < 0x80) {
             $i += 1;
             $length += 1;
         } else {
             if ($high < 0xe0) {
                 $i += 2;
             } else {
                 if ($high < 0xf0) {
                     $i += 3;
                 } else {
                     $i += 4;
                 }
             }
             $length += 2;
         }
     }
     return $length;
 }