LoginSignup
1
1

More than 1 year has passed since last update.

[PHP] データベースから取得した文字列などの定型文への、動的な値・変数の埋め込み/置き換え

Last updated at Posted at 2021-11-15

(サンプルソースはPHP/Laravelで記述しています。)

例えばメールの定型文や、記事のテンプレートなど、何かしらの文字列・文章がすでにある中へ、日時に応じて、ユーザーに応じてなど、動的な値をその時々で変えながら埋め込みたいということがあると思います。

文章・定型文中への、動的な値・変数の埋め込みを行うには、結論から言うと、str_replacemb_ereg_replace を使用して文字列を置き換えて表現します。

短いサンプルは以下の通りです。

sample.php
$replacement = [
    '%%word1%%' => 'こんばんは',
    '%%word2%%' => '綺麗'
];
$text = '%%word1%%、今夜は月が%%word2%%ですね。';
echo str_replace(array_keys($replacement), array_values($replacement), $text);
// 結果 => こんばんは、今夜は月が綺麗ですね。

要するに、置き換える前のキーワードが index かつ置き換えた後に表示したい文字列を value とした配列 $replacement を用意して、それら文字列を埋め込みたい文章を $text の変数として用意して、 str_replace(), array_keys(), array_values() の関数をそれぞれ駆使し動的に文章中へ値を埋め込み/置き換えしているということになります。

それぞれの関数について詳しくは公式のマニュアルをご参照ください。

str_replace — 検索文字列に一致したすべての文字列を置換する
array_keys — 配列のキーすべて、あるいはその一部を返す
array_values — 配列の全ての値を返す

下記はLaravelでメッセージテンプレートがDBに保存してあると仮定して、そのテンプレートのタイトルや本文、日付部分などをメッセージ閲覧時の情報で置き換えるサンプルソースとなります。

MessageController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Message;
use App\Repositories\MessageRepository;
use Carbon\Carbon;

class MessageController extends Controller
{
    // 説明上不要なメソッドなどは削除しています

    public function view(Request $request)
    {
        $messages = Message::all();
        $text = [];

        foreach ($messages as $message) {
            $text[] = $this->convert($message);
        }

        return view('pages/message/index', compact('text'));
    }

    public function convert($text)
    {
        $now = new Carbon();
        $deadline = $now->endOfMonth();

        $replacement = [
            '%%deadline%%' => $deadline->month . '月' . $deadline->day . '日',
            '%%now%%' => $now->year . '年' . $now->month . '月'
        ];
        return str_replace(array_keys($replacement), array_values($replacement), $text);
    }
}

仮に $message

"%%now%%のお知らせ\n
今月の締め切りは%%deadline%%となります。"

のような文字列が入っていた場合、 $replacement として定義されている配列の内容にそって文字列が置きかわりますので、実行時が2022年1月1日だったとすると、

"2022年1月のお知らせ\n
今月の締め切りは1月31日となります。"

のような文字列を得ることができます。

参考URL

メールの定型文に可変文字列(変数)を埋め込みたいとき
the_contentの置換を動的に行う
【PHP】複数文字列の置換(str_replace)
【PHP入門】文字列の置換 | str_replace・str_ireplace・strtr

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1