I'm looking for the php equivalent of pythons %
operator.
# PYTHON Example
foo = 'variable_string'
baz = 'characters'
new_string = 'my %(foo)s of %(baz)s' % locals()
My Vague php context:
Note: This is to demonstrate why I want to do this, it does not reflect any code.
// PHP Example context
class Controller {
...
// Singles quotes used in intentionally
// This template string is meant to be overloadable.
public $template = '<h1>{$title}</h1><h2>{$subheading}</h2>';
....
}
class View {
...
public function render($template) {
$title = 'variable string';
$subheading = 'some other variable stuff';
// Example of the python operator
return magically_put_variables_in_string(
$template,
magically_get_named_variables_from_scope()
);
}
...
}
magically_put_variables_in_string
implementation.array('$variable_name' => $variable_name)
Final Note: I have built a work around for my specific use case, however it does not satisfy the question.
A good approach would be strtr
:
strtr('<h1>{foo}</h1><h2>{bar}</h2>', array(
'{foo}' => $foo,
'{bar}' => $bar,
));
You can also use get_defined_vars()
to get an array of variables accessible in the current scope, though I personally prefer explicit enumeration.
One of the subtle advantages of using strtr
over str_replace
is that strtr
will not search the already-substituted portions of the string for further replacements. The manual page for str_replace
states:
Because
str_replace()
replaces left to right, it might replace a previously inserted value when doing multiple replacements.
It sounds like you are trying to do typecast swapping. You can do this with two functions print_f
and sprint_f
. The first will echo the output, the second will return a string. You can pass named variables into the functions like so:
// PHP Example context
class Controller {
...
// Singles quotes used in intentionally
// This template string is meant to be overloadable.
public $template = '<h1>%s</h1><h2>%s</h2>'; // Update this line
....
}
class View {
...
public function render($template) {
$title = 'variable string';
$subheading = 'some other variable stuff';
return sprint_f($template, $title, $subheading);
}
...
}
UPDATE:
You can also target variables in typecast swapping by adding numerical specifiers to the types. Say you want the title twice for some reason:
public $template = '<h1>%1$s</h1><h2>%2$s</h2><h3>%1$s</h3>';
That will typecast swap the first variable (second argument) in the sprint_f()
function in both the <h1>
and the <h3>
. The number you put in the specifier should match the argument location, so the %1$s
will be the first argument following the $template
and so on. You can have any number of typecast specifiers of any type. They are as follows:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With