Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to expand variables in a string
    primarykey
    data
    text
    <h3>Problem</h3> <p>I'd like to expand variables in a string in the same manner that variable in a double quoted string get expanded.</p> <pre><code>$string = '&lt;p&gt;It took $replace s&lt;/&gt;'; $replace = 40; expression_i_look_for; </code></pre> <p><code>$string</code> should become <code>'&lt;p&gt;It took 40 s&lt;/&gt;';</code></p> <p>I see a obvious solution like this:</p> <pre><code>$string = str_replace('"', '\"', $string); eval('$string = "$string";'); </code></pre> <p>But I really don't like it, because eval() is insecure. Is there any other way to do this ?</p> <h3>Context</h3> <p>I'm building a simple templateing engine, that's where I need this.</p> <p>Example Template (view_file.php)</p> <pre><code>&lt;h1&gt;$title&lt;/h1&gt; &lt;p&gt;$content&lt;/p&gt; </code></pre> <p>Template rendering (simplified code):</p> <pre><code>$params = array('title' =&gt; ...); function render($view_file, $params) extract($params) ob_start(); include($view_file); $text = ob_get_contents(); ob_end_clean(); expression_i_look_for; // this will expand the variables in the template return $text; } </code></pre> <p>The expansion of the variables in the template simplifies it's syntax. Without it, the above example template would be:</p> <pre><code>&lt;h1&gt;&lt;?php echo $title;?&gt;&lt;/h1&gt; &lt;p&gt;&lt;?php echo $content;?&gt;&lt;/p&gt; </code></pre> <p>Do you think this approach is good ? Or should I look in another direction ?</p> <h3>Edit</h3> <p>Finally I understand that there is no simple solution due to flexible way PHP expands variables (even <code>${$var}-&gt;member[0]</code> would be valid.</p> <p>So there are only two options:</p> <ol> <li>Adopt an existing full fledged templating system</li> <li>Stick with something very basic that essentially is limited to including the view files via <code>include</code>.</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload