Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a variable within a string with PHP?

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?

like image 565
Andrew Avatar asked May 06 '09 08:05

Andrew


People also ask

How do you replace a variable in a string?

You use the replace() method by: assigning the initial string or strings to a variable. declaring another variable. for the value of the new variable, prepending the new variable name with the replace() method.

How can I replace part of a string in PHP?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

What is variable substitution PHP?

Variable substitution is a way to embed data held in a variable directly into string literals. PHP parse double-quoted (and heredoc) strings and replace variable names with the variable's value. By BrainBell. May 12, 2022.

How can I replace multiple characters in a string in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.


2 Answers

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);
like image 178
duckyflip Avatar answered Oct 06 '22 00:10

duckyflip


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...

like image 39
Svish Avatar answered Oct 05 '22 23:10

Svish