Python-like .format() in php

400 Views Asked by At

I have the following array:

$matches[0] = "123";
$matches[1] = "987";
$matches[2] = "121";

And the following string:

$result = "My phone number is {0} and police number is {2}";

I would like to replace the {} placeholder based on the $matches array, in case there is no match for placeholder display nothing instead.

What is the best way to achieve that, or do you know a better solution to my problem?

(Right now I am building the system, so instead of curly brackets I could use any other symbol)

UPDATE

In python this is possible using .format() function.

1

There are 1 best solutions below

4
Casimir et Hippolyte On BEST ANSWER

You can do it with vsprintf, you don't have to change the order of items if you give the number (from 1) of your item like this: %n$s (where n is the number):

$matches = [ "123", "987", "121"];
$result = 'My phone number is %1$s and police number is %3$s';

$res = vsprintf($result, $matches);

Note that you have to put the formatted string between single quotes, otherwise $s will be interpreted as a variable and replaced with nothing.

(vprintf and vsprintf are designed for arrays, but you can do the same thing with printf and sprintf for separated variables, it works the same)


If you can't change your original Python formatted string, the way is to use preg_replace_callback:

$matches = [ "123", "987", "121"];
$result = 'My phone number is {0} and police number is {2}';

$res = preg_replace_callback('~{(\d+)}~', function ($m) use ($matches) {
    return isset($matches[$m[1]]) ? $matches[$m[1]] : $m[0];
}, $result);

or you can build an associative array where the keys are placeholders and values your array values, and use strtr for the replacement:

$matches = [ "123", "987", "121"];
$result = 'My phone number is {0} and police number is {2}';

$trans = array_combine(
    array_map(function ($i) { return '{'.$i.'}'; }, array_keys($matches)),
    $matches
);

$result = strtr($result, $trans);