Strict Standards: Non-static method Protector::getInstance() should not be called statically in /home/suehirogari/suehirogari.com/xoops_trust_path/modules/protector/include/precheck_functions.php on line 12

Strict Standards: Non-static method XCube_Root::getSingleton() should not be called statically in /home/suehirogari/suehirogari.com/public_html/include/common.php on line 18

Deprecated: Non-static method XCube_Root::getSingleton() should not be called statically, assuming $this from incompatible context in /home/suehirogari/suehirogari.com/public_html/modules/user/preload/Primary/Primary.class.php on line 13
Smartyにtruncateという文字列修正の関数がある。指定した文字数で文字列を切り捨てるという便利なものなのだが、マルチバイト文字列に対してこれを使うと文字化けが起こってしまう。 | 社内SEのウェブ制作

2011.04.04xoopsズープス

Smartyにtruncateという文字列修正の関数がある。指定した文字数で文字列を切り捨てるという便利なものなのだが、マルチバイト文字列に対してこれを使うと文字化けが起こってしまう。

xoopsの 文字を指定した文字数で切り捨てて、詳細ページへ移動させる方法として、
truncateという Smarty関数 を利用できる。

ただし、日本語のようなマルチバイト文字列に対してこの関数を利用すると文字化け(◇の黒の中に?ハテナ)が表示されたりする。

そこで、
http://xoopscube.jp/modules/newbb/viewtopic.php?topic_id=4440&forum=17&post_id=23846 

に記載のあった、 mbtruncate を利用して、適当な文字列で文字を丸める。

<?php

/*
* Smarty plugin
* -------------------------------------------------------------
* Type: modifier
* Name: mbtruncate
* Purpose: Truncate a string to a certain length if necessary,
* optionally splitting in the middle of a word, and
* appending the $etc string.
* -------------------------------------------------------------
*/
function smarty_modifier_mbtruncate($string, $length = 80, $etc = '...',
$break_words = false)
{
if ($length == 0)
return '';

if (strlen($string) > $length) {
$length -= strlen($etc);
if (!$break_words)
$string = preg_replace('/\s+?(\S+)?$/', '', mb_strcut($string, 0, $length+1));

return mb_strcut($string, 0, $length).$etc;
} else
return $string;
}
?>

をmodifier.mbtruncate.phpとして保存



ファイルは modifer.mbtruncate.php をダウンロードして
/class/smarty/plugins/modifier.mbtruncate.phpに保存

モジュールのテンプレートのタイトルやら記事やらの記述部に【|mbtruncate:30】をくっつける。
30はバイト数
例えば、d3pipeの記事タイトル
<{$entry_headline4disp}>

<{$entry_headline4disp|mbtruncate:30}>
とすれば、OK.
デフォルトは文字数を超えた部分は【...】が入る。
この設定は、modifier.mbtruncate.phpの
$etc = '...',
の変更で対応。


このカテゴリの人気記事



  • コメント (0)
  • トラックバック (0)
  • 閲覧 (26286)

トラックバック

トラックバックpingアドレス http://www.suehirogari.com/modules/blog/tb.php/179

コメントの投稿

コメント投稿に関するルール : コメントは全て承認が必要

キーワードでサイト内を検索
人気のエントリ