Advanced Custom Fieldsで~を使った範囲のある金額表示

Filed under: php — kdcs @ 25年10月6日 月曜日

数字で入力した金額にカンマを付けたり、前に~や後ろに~を付けるだけでなく4000~10000など範囲のある金額を表示させる方法。

~が3種類(チルダmac・波ダッシュwindows・半角チルダ)あるため、~に絞らず数字だけ抽出して半角とカンマ処理させることにした。最終的に金額の後ろに円を付ける。

※例は宴会プラン用(banquet_price・banquet_tilde_position)

<?php
$price_raw = get_field('banquet_price'); // 例: "4000~10000" や "4000"
$tilde = get_field('banquet_tilde_position'); // 「before」「after」「none」

if ($price_raw) {
    // 全角数字を半角に変換
    $price_raw = mb_convert_kana($price_raw, 'n');

    // 数字部分だけ抽出してカンマを付ける
    $price_text = preg_replace_callback('/\d+/', function($matches) {
        return number_format($matches[0]);
    }, $price_raw);

    // 「円」を最後に追加
    $price_text .= '円'
;
    // 「~」の位置を制御
    if ($tilde === 'before') {
        $formatted_banquet_price = '~' . $price_text;
    } elseif ($tilde === 'after') {
        $formatted_banquet_price = $price_text . '~';
    } else {
        $formatted_banquet_price = $price_text;
    }
}
?>

サイト内検索

カテゴリー

最近の投稿

« |Advanced Custom Fieldsで~を使った範囲のある金額表示| »
↑上に戻る