How to replace a variable within a string with PHP

2019-02-17 15:02发布

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条回答
太酷不给撩
2楼-- · 2019-02-17 15:15
$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

查看更多
Root(大扎)
3楼-- · 2019-02-17 15:20

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

查看更多
对你真心纯属浪费
4楼-- · 2019-02-17 15:21

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

查看更多
乱世女痞
5楼-- · 2019-02-17 15:27

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);
查看更多
不美不萌又怎样
6楼-- · 2019-02-17 15:41

try dynamic variables:

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

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

查看更多
登录 后发表回答