php 如何替换字符串中的占位符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8718905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:21:03  来源:igfitidea点击:

how to replace a placeholder in a string?

php

提问by Alica Kindel

Not very sure how to word this question but I'll give an example.

不太确定如何表达这个问题,但我会举一个例子。

$string = 'Hey, $name. How are you?'; 

When I post this string, $namedoesn't change. How can I make it so I can put something like +name+so it changes to the name. I've tried seaching for it but I don't know what to search for so I don't have any luck. It's probably really simple but i'm just blanking out. Thanks

当我发布此字符串时,$name不会改变。我怎样才能做到这一点,以便我可以将类似的+name+内容更改为名称。我试过搜索它,但我不知道要搜索什么,所以我没有任何运气。这可能真的很简单,但我只是空白。谢谢

回答by Brad Christie

You can use place-holders and str_replace. Or use PHP's built-in sprintfand use %s. (And as of v4.0.6 you can swap the ordering of arguments if you'd like).

您可以使用占位符和str_replace. 或者使用 PHP 的内置sprintf并使用%s. (从 v4.0.6 开始,您可以根据需要交换参数的顺序)。

$name = 'Alica';

// sprintf method:
$format = 'Hello, %s!';
echo sprintf($format, $name); // Hello, Alica!

// replace method:
$format = "Hello, {NAME}!";
echo str_replace("{NAME}", $name, $format);

And, for anyone wondering, I understood that is trouble templating a string, not PHP's integrated concatenation/parsing. I just assume keep this answer up though as I'm still not 100% sure this OP's intent

而且,对于任何想知道的人,我明白这是模板字符串的麻烦,而不是 PHP 的集成连接/解析。我只是假设保留这个答案,因为我仍然不是 100% 确定这个 OP 的意图

回答by Nick

I've always been a fan of strtr.

我一直是strtr.

$ php -r 'echo strtr("Hi @name. The weather is @weather.", ["@name" => "Nick", "@weather" => "Sunny"]);'
Hi Nick. The weather is Sunny.

The other advantage to this is you can define different placeholder prefix types. This is how Drupal does it; @indicates a string to be escaped as safe to output to a web page (to avoid injection attacks). The format_stringcommand loops over your parameters (such as @nameand @weather) and if the first character is an @, then it uses check_plainon the value.

另一个优点是您可以定义不同的占位符前缀类型。Drupal 就是这样做的;@指示要转义的字符串以安全输出到网页(以避免注入攻击)。的FORMAT_STRING命令遍历您的参数(如@name@weather),并且如果所述第一字符是一个@,那么它使用check_plain上的值。

回答by Tim Cooper

You should be wrapping the string in double quotes (") if you want variables to be expanded:

"如果要扩展变量,则应将字符串括在双引号 ( ) 中:

$name = "Alica";
$string = "Hey, $name. How are you?"; // Hey, Alica. How are you?

See the documentation.

请参阅文档

回答by Josh

A third solution, no better or worse than the aforementioned, is concatenation:

第三种解决方案,并不比上述更好或更差,是串联:

echo 'Hello '. $name .'!!!';

echo 'Hello '. $name .'!!!';