Eldho NewAge
Eldho NewAge

Reputation: 1333

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?

Upvotes: 0

Views: 21897

Answers (2)

user2917245
user2917245

Reputation:

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.

Upvotes: 9

James Paterson
James Paterson

Reputation: 2890

If the white space is just whitespace as in space characters, you can use the function trim() (Docs) to strip it. Replace $options[myname] with trim($options[myname]).

If it's the string "[whitespace]", you can use preg_replace() (Docs) like: preg_replace("/[whitespace]/","",$options[myname])

Upvotes: 0

Related Questions