繁体   English   中英

PHP是否具有类似于Python的f字符串函数的字符串函数? (不是str.format())

[英]Does PHP have a string function like Python's f-string function? (not str.format())

我是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文档都有几种方法来进行字符串连接,但是我实际上并没有找到这样的东西。

您可以使用点表示法将任何变量附加到具有字符串连接的任何其他变量中:

$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM