【问题标题】:Does PHP have a string function like Python's f-string function? (not str.format())PHP 是否有类似 Python 的 f-string 函数的字符串函数? (不是 str.format())
【发布时间】:2019-07-19 09:50:10
【问题描述】:

我是 PHP 新手,所以请原谅这个问题。

我想知道 PHP 是否有字符串格式函数,例如 Python 的 f-strings 函数,而不是 str.format()。我看过一些关于这个主题的帖子,但大多数被接受为答案的例子都是指 Python 处理格式化字符串 str.format() 的旧方法。在我的情况下,我想使用格式化的字符串来构建一个变量,例如(Python):

f_name = "John"
l_name = "Smith"
sample = f`{f_name}'s last name is {l_name}.`
print(sample)

我知道我可以使用 (PHP):

 $num = 5;
 $location = 'tree';
 $format = 'There are %d monkeys in the %s';
 echo sprintf($format, $num, $location);

但是如果我想使用$format 作为变量呢?主要思想是基于其他变量创建一个动态变量,例如:

$db_type = $settings['db_type'];  # mysql
$db_host = $settings['db_host'];  # localhost
$db_name = $settings['db_name'];  # sample

var $format = "%s:host=%s; dbname=%s";

# Not sure what to do after that, but I can use string concatenation:

var $format = $db_type + ":host=" + $db_host + "; dbname=" + $db_name;
var $connection = new PDO($format, $db_user, $db_password);

注意:我知道根据 PHP 文档有几种方法可以进行字符串连接,但是我真的找不到这样的东西。

【问题讨论】:

  • 不回显 sprintf 结果,只需将其分配给变量。
  • 是的,使用 PHP 模板:$f_name = "John"; $l_name = "Smith"; $sample = "{$f_name}'s last name is {$l_name}."

标签: php string f-string


【解决方案1】:

您可以使用点符号将任何变量附加到带有string concatenation 的任何其他变量:

$num = 5;
$location = 'tree';
$output = 'There are ' . $num . ' monkeys in the ' . $location; // There are 5 monkeys in the tree

或.= 表示法:

$a = "Hello ";
$b = "World";
$a .= $b; // $a now contains "Hello World"

您还可以使用 双引号 中包含的单个字符串,它会自动评估变量。请注意,单引号不评估变量:

$num = 5;
$location = 'tree';
echo 'There are $num monkeys in the $location'; // There are $num monkeys in the $location
echo "There are $num monkeys in the $location"; // There are 5 monkeys in the tree

这在分配给变量时也是一样的:

$num = 5;
$location = 'tree';
$output = "There are $num monkeys in the $location"; // There are 5 monkeys in the tree

这可以用大括号进一步说明:

$output = "There are {$num} monkeys in the {$location}"; // There are 5 monkeys in the tree
// OR
$output = "There are ${num} monkeys in the ${location}"; // There are 5 monkeys in the tree

【讨论】:

  • 非常清楚!显然我找错地方了。
  • 那么,美元符号应该放在{之前还是之后?
  • @Dharman -- 对于大多数 的情况,这无关紧要,尽管{$var} 是首选。请参阅this question... 你自己问的:)
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 2011-08-26
  • 2011-08-01
  • 2013-12-11
  • 2011-10-26
  • 1970-01-01
  • 2011-08-20
  • 2011-03-27
相关资源
最近更新 更多