How to replace a variable within a string with PHP?

15,154

Solution 1

You can actually use the sprintf function which will return a formatted string and will put your variables on the place of the placeholders.
It also gives you great powers over how you want your string to be formatted and displayed.

$output = sprintf("Here is the result: %s for this date %s", $result, $date);

Solution 2

If you use %s, I think that is the same placeholder that printf uses for a string. So you could do:

$text = sprintf($message, "replacement text");

Think that should work at least...

Solution 3

$find = array(
     '#name#',
     '#date#'
);
$search = array(
     'someone\'s name',
     date("m-d-Y")
);
$text_result = str_replace($find, $search, $text);

I'm usually using this for my code, fetching the $text from some text/html files then make the $text_result as the output

Solution 4

You can use sprintf, which works in a very similar way to C's printf and sprintf functions.

Share:
15,154
Mike
Author by

Mike

Updated on June 04, 2022

Comments

  • Mike
    Mike almost 2 years

    So I have some PHP code that looks like:

    $message = 'Here is the result: %s';
    

    I just used %s as an example. It's basically a placeholder for whatever will go there. Then I pass the string to a function and I want that function to replace the %s with the value.

    What do I need to do to achieve this? Do I need to do some regex, and use preg_replace(), or something? or is there a simpler way to do it?