文字列を置換(replace)

広告

「replace」は文字列に含まれる一部の文字列を他の文字列で置換します。書式は次の通りです。

{$変数名|replace:"対象の文字列":"置換する文字列"}

1番目のパラメータに置換の対象となる文字列を指定し2番目のパラメータに置き換える文字列を指定します。

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

{$var|replace:"orange":"melon"}

サンプルプログラム

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

sample20-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', 'I like orange');

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

?>

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

sample20-1.tpl

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

<h1>{$title}</h1>
<p>{$msg}</p>
<p>{$msg|replace:"orange":"melon"}</p>

</body>
</html>

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

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

文字列を置換(replace)

( Written by Tatsuo Ikura )