How to replace a variable in a string using PHP?

So I have PHP code that looks like this:

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

I just used% s as an example. This is basically a placeholder for whatever. Then I pass the string to the function, and I want this function to replace% s with a value.

What do I need to do for this? Do I need to do some regular expression and use preg_replace () or something else? or is there an easier way to do this?

+5
source share
5 answers

sprintf, . < > .

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

%s, , , printf . , :

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

, ...

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

, $text /html $text_result

+3

sprintf, C printf sprintf.

+2

:

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

% s $s,

-3
source

All Articles