5

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?

5 Answers 5

21

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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

Comments

2

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

Comments

-3

try dynamic variables:

$placeholder = 's';
str_replace("%".$placeholder,$$placeholder,$message);

then %s will be replaced with $s, the variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.