空白・改行・タブを置換(strip)

広告

「strip」は文字列に含まれる空白・改行・タブを1つの空白に置き換えます。書式は次の通りです。

{$変数名|strip[:置き換える文字]}

置き換える文字を指定しなかった場合は1つの空白に置き換えられます。

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

住所は {$address|strip} です

また1つの空白ではなく別の文字に置き換えたい場合は次のように記述します。

住所は {$address|strip:"str"} です

サンプルプログラム

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

sample6-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', "こんにちは¥nお元気ですか。   では。");

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

?>

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

sample6-1.tpl

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

<h1>{$title}</h1>
<p>{$msg}</p>
<p>{$msg|strip}</p>
<p>{$msg|strip:' '}</p>

</body>
</html>

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

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

空白・改行・タブを置換(strip)

表示されたものを見ると違いが分かりにくいですが表示されたHTMLページのソースを見てみると置換されていることが分かります。

空白・改行・タブを置換(strip)

( Written by Tatsuo Ikura )