簡體   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