vsprintf or sprintf with named arguments, or simple template parsing in PHP

Late to the party, but you can simply use strtr to “translate characters or replace substrings”

<?php

$hours = 2;
$minutes = 24;
$seconds = 35;

// Option 1: Replacing %variable
echo strtr(
    'Last time logged in was %hours hours, %minutes minutes, %seconds seconds ago',
    [
        '%hours' => $hours,
        '%minutes' => $minutes,
        '%seconds' => $seconds
    ]
);

// Option 2: Alternative replacing {variable}
echo strtr(
    'Last time logged in was  {hours} hours, {minutes} minutes, {seconds} seconds ago',
    [
        '{hours}' => $hours,
        '{minutes}' => $minutes,
        '{seconds}' => $seconds
    ]
);

// Option 3: Using an array with variables:
$data = [
    '{hours}' => 2,
    '{minutes}' => 24,
    '{seconds}' => 35,
];

echo strtr('Last time logged in was {hours} hours, {minutes} minutes, {seconds} seconds ago', $data);

// More options: Of course you can replace any string....

outputs the following:

Last time logged in was 2 hours, 24 minutes, 35 seconds ago

Leave a Comment