Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to put named variables in string With the string defined before the variables

Tags:

php

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()
        );
    }
    ...
}
  • Specifically I want the most canonical magically_put_variables_in_string implementation.
  • I cannot assume I will be able to use anything from later than php 5.3
  • I do not mind passing an explicit array('$variable_name' => $variable_name)
  • Points for doing it without defining a new function.

Final Note: I have built a work around for my specific use case, however it does not satisfy the question.

like image 847
ThorSummoner Avatar asked Nov 30 '22 01:11

ThorSummoner


2 Answers

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.

like image 174
DCoder Avatar answered Dec 04 '22 03:12

DCoder


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:

  • % - a literal percent character. No argument is required.
  • b - the argument is treated as an integer, and presented as a binary number.
  • c - the argument is treated as an integer, and presented as the character with that ASCII value.
  • d - the argument is treated as an integer, and presented as a (signed) decimal number.
  • e - the argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
  • E - like %e but uses uppercase letter (e.g. 1.2E+2).
  • f - the argument is treated as a float, and presented as a floating-point number (locale aware).
  • F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
  • g - shorter of %e and %f.
  • G - shorter of %E and %f.
  • o - the argument is treated as an integer, and presented as an octal number.
  • s - the argument is treated as and presented as a string.
  • u - the argument is treated as an integer, and presented as an unsigned decimal number.
  • x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
  • X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).
like image 45
Matthew R. Avatar answered Dec 04 '22 04:12

Matthew R.