Search code examples
phpsmartywhitespacetrim

SMARTY : Remove whitespace at the beginning or end of my string in Smarty template?


Here's my string seperated by commas (,) $myStr = "One, Two,Three, Four , Five ,Six "

I am able successfully explode it {assign var="options" value=","|explode:$myStr}

But I also would like to remove whitespace at the beginning or end from each string when outputting it. In other words: I am looking for a SMARTY function equivalent to PHP's built-in trim($mystr) function. PHP trim will remove the start and end white-spaces if it present, otherwise return the actual string.

{section name=myname loop=$options}
   {$options[myname]}
{/section}

The code above would output:

One
Two
Three
[whitespace]Four[whitespace]
[whitespace]Five[whitespace]
Six[whitespace]

How can I trim whitespaces?


Solution

  • There is {strip}{/strip} in smarty. Whitespaces will be removed between theese tags.

    {$var|substr:0:-1} would remove last character in your case the whitespace. {$var|substr:1} would remove the first character from string.

    all php-functions can be used as modifiers implicitly (more below) and modifiers can be combined

    from docs {$var|trim} in smarty is equal to trim($var) in php.

    There is another way. Using {php}{/php} tags in in smarty to able to use php built-in trim() function, but that makes no sense to me. Why would you even want to put smarty variable back to php if it was included by php? Nonsense.