I have a string such as :
"Hello ? My name is ? I am ? years old"
And I have an array such as :
['George','Jonathan',35]
I'd like a result of combining and returning:
`Hello "Geroge" My name is "Jonathan" I am "35" years old`
How do i accomplish this in php?
I tried using str_ireplace but it said "array to string conversion"
If you are able to change the way you define placeholders in your string, you should use sprintf. Check out the manual.
Simple example:
$result = sprintf("Hello %s My name is %s I am %d years old", 'George', 'Jonathan', 35);
In your case, you could use the splat operator (php >= 5.6) in order to pass the variables:
$variables = ['George', 'Jonathan', 35];
$result = sprintf("Hello %s My name is %s I am %d years old", ...$variables);
As others pointed out, the vsprintf function may be a better way. See devpro's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With