Showing posts with label smarty. Show all posts
Showing posts with label smarty. Show all posts

2011/05/18

Multiple Preg replace in PHP

You can do multiple preg replace with one function call, for example,

PHP, using GeSHi 1.0.8.8
  1. $subject = "{hello}";
  2. $patterns = array("/{/", "/}/");
  3. $replaces = array("{ldelim}", "{rdelim}");
  4. echo preg_replace($patterns, $replaces, $subject); 

Guess what your get? you get,

{ldelim{rdelim}hello{rdelim}

The reason you get this is that perg_replace executes multiple patterns one by one, so ‘{‘ is replaced by ‘{ldelim}’, and then ‘{ldelim}’ is replaced by ‘ {ldelim{rdelim}’.

I believe this is not what you wanted to get. You only want one ‘pattern’ is replaced once. So you can do this,

PHP (brief), using GeSHi 1.0.8.8
  1. $title = "{abdcd}";
  2. $patterns = array("/{/", "/}/");
  3. $replaces = array("LC", "RC");
  4. $title = preg_replace($patterns, $replaces, $title);
  5.  
  6. $patterns = array("/LC/", "/RC/");
  7. $replaces = array("{ldelim}", "{rdelim}");
  8. echo preg_replace($patterns, $replaces, $title);

Finally, you get,

{ldelim}hello{rdelim}

Note that in smarty template, to keep brace, you have to change ‘{ ‘or ‘} ‘to ‘{ldelim}’ or ‘{rdelim}’, or add {literal} and {/literal} around the code that you don’t want smarty engine to interpret it.

2010/07/09

Small php script in Smarty templates

Sometimes, we wanted to run a small PHP scripts inside Smarty templates. That’s good that we don’t need to touch PHP source file to add smarty variables. Here is an example,

In the PHP source code, I have smarty variable named phpvar,

<?php
$phpvar = "Hello World";
$smarty->assign('phpvar', $phpvar);
?>

And in the smarty tempate file, I wanted to split phpvar into tow variable. Sure, you can update source code, to include 2 variables, but sometime, you may do it in the template file. Here is how,

{if preg_match("/(.+)\s+(.+)/", $phpvar, $matches)}
<li>{$matches.1}</li>
<li>{$matches.2}</li>
{/if}

 

2010/03/19

smarty dollar to cent

In a project we have a smarty variable presenting a dollar value like ‘1.23’, or ‘.06’. And we wanted to show cent value when the value less than one dollar, for exmaple,

  1. “.78” will be “78”
  2. “.06” will be “6”

Instead of crating a new smarty variable in php, here is a workaround I made in the template.

{*here $dollar_per is in dollar value*}
{if $dollar_per && $dollar_per < 1}
   {if $dollar_per < 0.1} {*ex. 0.06*}
   {assign var="cent_per" value=$dollar_per|substr:2} {*get 6*}
   {assign var="cent_per" value="&nbsp;"|cat:$cent_per} {*add space before 6 in my case*}
   {else} {*ex. 0.78*}
   {assign var="cent_per" value=$dollar_per|substr:1} {*get 78*}
   {/if}
{/if}

Note: substr and cat were used!