I'm new to PHP, so please excuse the question.
I was wondering if PHP had a string format function such as Python's f-strings function, not str.format(). I have seen a few posts regarding the subject, but most of the examples accepted as answers refer to Python's older way of dealing with formatted strings str.format()
. In my case I would like to build a variable using a formatted string for example (Python):
f_name = "John"
l_name = "Smith"
sample = f`{f_name}'s last name is {l_name}.`
print(sample)
I know I can use (PHP):
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
but what if I want to use $format
as a variable? The main idea is to create a dynamic variable based on other variables for instance:
$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);
NOTE: I'm aware that there are several ways to do string concatenation per the PHP documentation, however I was not really able to find anything like this.