I'm not exactly sure what this is called but is common in programming, often using the ? instead of the % which I use in this example.
Say I have a string:
"How many % does it take the build a % out of aluminum cans?"
And I want to replace the % symbol with specific values from an array based on their index and the position in the string. In this case:
['robots', 'laser gun']
The result would be:
How many robots does it take to build a laser gun out of aluminum cans?
Is there any way to easily accomplish this in PHP?
just adding to the options :-)
<?php
$s= "How many %1\$s does it take the build a %2\$s out of aluminum cans?";
$a=array('robots', 'laser gun');
echo vsprintf($s,$a)
?>
I wrote this up and tested it, works!
$randomstring = "How many % does it take the build a % out of aluminum cans?";
$array = array("robots", "laser gun");
for($x = 0;$x != count($array);$x++){
$randomstring = preg_replace('/%/', $array[$x], $randomstring, 1);
}
echo $randomstring;
Perhaps
sprintf ( "How many %s does it take the build a %s out of aluminum cans?", "robots", "laser gun" )
The following code does the job:
$string = 'How many % does it take the build a % out of aluminum cans?';
$placeholders = ['robots', 'laser gun'];
echo call_user_func_array('sprintf', array_merge([str_replace('%', '%s', $string)], $placeholders));
If you label the tokens then you can use strtr
to search and replace the values. Using named tokens makes your code slightly easier to read.
$str = "How many {thing} does it take the build a {weapon} out of aluminum cans?";
echo strtr($str, [
'{thing}' => 'robots',
'{weapon}' => 'laser gun',
]);