Python-like.format () in php

I have the following array:

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

And the following line:

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

I would like to replace the {}array-based placeholder $matchesif there are no matches so that nothing is displayed instead.

What is the best way to achieve this or do you know the best solution to my problem?

(Now I am building a system, so instead of curly braces I can use any other character)

UPDATE

In python, this is possible with a function .format().

+4
source share
1 answer

vsprintf, , ( 1) : %n$s ( n - ):

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

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

, , $s .

(vprintf vsprintf , printf sprintf , )


Python, 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);

, , strtr :

$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);
+4

Source: https://habr.com/ru/post/1674895/


All Articles