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.
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):Note that you have to put the formatted string between single quotes, otherwise
$swill be interpreted as a variable and replaced with nothing.(
vprintfandvsprintfare designed for arrays, but you can do the same thing withprintfandsprintffor separated variables, it works the same)If you can't change your original Python formatted string, the way is to use
preg_replace_callback:or you can build an associative array where the keys are placeholders and values your array values, and use
strtrfor the replacement: