改行文字「¥n」を<br />タグへ置換(nl2br)

広告

「nl2br」は文字列に含まれる改行文字「¥n」をHTMLタグである<br />タグに置き換えます。書式は次の通りです。

{$変数名|nl2br}

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

{$msg|nl2br}

サンプルプログラム

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

sample8-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は¥nPHPで使う¥nテンプレートエンジンです");

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

?>

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

sample8-1.tpl

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

<h1>{$title}</h1>
<p>{$msg|nl2br}</p>

</body>
</html>

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

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

改行文字「¥n」を<br />タグへ置換(nl2br)

表示されたHTMLページのソースを確認してみます。

改行文字「¥n」を<br />タグへ置換(nl2br)

サンプルプログラム

先ほどは文字列の中に記述された「¥n」を置換していましたが、今度はヒアドキュメントなどを使って複数行に記述された文字列の中の改行を変換するサンプルを試してみます。

sample8-2.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', '修飾子のテスト');
$msg=<<<EOT
こんにちは
明日も晴れるでしょうか
ではまた
EOT;
$smarty->assign('msg', $msg);

$smarty->display('sample8-2.tpl');

?>

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

sample8-2.tpl

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

<h1>{$title}</h1>
<p>{$msg|nl2br}</p>

</body>
</html>

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

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

改行文字「¥n」を<br />タグへ置換(nl2br)

表示されたHTMLページのソースを確認してみます。

改行文字「¥n」を<br />タグへ置換(nl2br)

( Written by Tatsuo Ikura )