文字間に空白を挿入(spacify)

広告

「spacify」は文字列に含まれる各文字の間に空白を挿入します。書式は次の通りです。

{$変数名|spacify[:挿入する文字列]}

デフォルトでは挿入される文字は半角スペース1つです。1番目のパラメータに文字列を指定することで、文字間に挿入される文字を変更することが出来ます。

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

{$var|spacify}
{$var|spacify:"_"}

サンプルプログラム

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

sample18-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('msg', 'Smarty is a template engine for PHP');

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

?>

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

sample18-1.tpl

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

<h1>{$title}</h1>
<p>{$msg}</p>
<p>{$msg|spacify}</p>
<p>{$msg|spacify:"_"}</p>

</body>
</html>

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

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

文字間に空白を挿入(spacify)

( Written by Tatsuo Ikura )