Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple string replace against character [duplicate]

Tags:

string

php

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"

like image 423
somejkuser Avatar asked Aug 14 '26 11:08

somejkuser


1 Answers

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.

like image 112
Barthy Avatar answered Aug 17 '26 02:08

Barthy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!