単語数をカウント(count_words)

広告

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

{$変数名|count_words}

単語の区切りは空白です。

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

単語数は {$var|count_words} 個です

サンプルプログラム

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

sample15-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('sample15-1.tpl');

?>

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

sample15-1.tpl

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

<h1>{$title}</h1>
<p>{$var}</p>
<p>単語数は {$var|count_words} 個です</p>

</body>
</html>

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

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

単語数をカウント(count_words)

( Written by Tatsuo Ikura )