Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smarty getting substring of a var with strpos as start and strlen as end

I am having issue formatting variables in smarty. I was wondering what is the best way to do it. Basically i have a string "ABC | DEFGH" i want smarty to get the substring of "DEFGH" How would i go about doing this?

{$var|substr:strpos:"|":strlen}

doesn't work

like image 985
KJYe.Name Avatar asked Dec 08 '10 16:12

KJYe.Name


2 Answers

Just solved this without setting var back in PHP, and by using the built-in function wrappers.

Assuming that: $var = "ABC|DEFGH";

{assign var="bar_at" value=$var|strpos:"|"}
<li>{$var}</li>
<li>{$var|substr:0:$bar_at}</li>
<li>{$var|substr:$bar_at+1}</li>

This will print:

  • ABC|DEFGH
  • ABC
  • DEFGH
  • like image 182
    Jimby Avatar answered Sep 19 '22 13:09

    Jimby


    Some info about Smarty 3 in case if someone want to achieve the same in Smarty 3 and not in Smarty 2:

    The first thing is that you need to add parentheses to make it work. substr:$bar_at+1 won't work but substr:($bar_at+1) will work.

    But in fact you can use simpler syntax:

    {assign var="var" value="ABC | DEFGH"}
    
    {$var|substr:($var|strpos:"|"+1)}
    

    This will give you DEFGH with space at the beginning (before and | are spaces inside var in your question and in my example) and as you want to get string without space you should use in this case +2 instead of +1:

    {$var|substr:($var|strpos:"|"+2)}
    

    Those above were tested in Smarty 3.1.19.

    You should also know that in previous versions (before Smarty 3.1) if you have in your string UTF-8 characters you should rather use mb_ functions.

    As of Smarty 3.1 in case if mbstring extension is installed Smarty automatically uses mb_ functions in that case so there won't be any problem with utf-8 characters.

    You can read more about Smarty utf-8 encoding

    like image 41
    Marcin Nabiałek Avatar answered Sep 19 '22 13:09

    Marcin Nabiałek