文字数をカウント(count_characters)

広告

「count_characters」は対象の変数に含まれる文字数をカウントします。書式は次の通りです。

{$変数名|count_characters[:空白をカウントする]}

1番目のパラメータで空白文字を1文字としてカウントするかどうかを指定します。デフォルトは「false」です。空白もカウントする場合は「true」を指定して下さい。

なお文字数はバイト数でカウントします。日本語などのマルチバイト文字の場合注意して下さい。

具体的には次のように記述します。

文字数は {$var|count_characters:true} 個です

サンプルプログラム

では簡単なサンプルプログラムを作成して試してみます。

sample14-1.php

<?php

require_once('Smarty.class.php');

$smarty = new Smarty();

$smarty->template_dir = 'd:/smartysample/modifier/templates/';
$smarty->compile_dir  = 'd:/smartysample/modifier/templates_c/';
$smarty->config_dir   = 'd:/smartysample/modifier/configs/';
$smarty->cache_dir    = 'd:/smartysample/modifier/cache/';

$smarty->assign('title', '修飾子のテスト');
$smarty->assign('var', 'Smarty is a template engine for PHP');

$smarty->display('sample14-1.tpl');

?>

上記を「sample14-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥modifier」に保存します。

sample14-1.tpl

{* Smarty modifier/sample14-1.tpl *}
<html>
<head>
<title>Smarty Test</title>
</head>
<body>

<h1>{$title}</h1>
<p>{$var}</p>
<p>文字数は {$var|count_characters} 個です</p>
<p>文字数は {$var|count_characters:true} 個です(空白含む)</p>

</body>
</html>

上記を「sample14-1.tpl」の名前で「D:¥smartysample¥modifier¥templates」に保存します。

そしてブラウザから「http://localhost/smarty/modifier/sample14-1.php」へアクセスして下さい。

文字数をカウント(count_characters)

( Written by Tatsuo Ikura )