Emulating PHP’s substr() with Smarty [sort of]

Today I had a requirement to strip off the first 9 digits from a string from within a Smarty template. The system using Smarty is *totally* locked down so no access to plugins or using php functions as modifiers so I could not simply do $string=substr($string,9); or even {assign var=”shorterThing” value=$thing|substr:9}

In the end I used a regexp:
/^[0-9 ]{9}/
Which reads “Match from the beginning of the string digits or a space exactly 9 characters long”.

Unfortunately, Smarty uses {} as special characters so I had to further jump though hoops to get it to work by using the {capture} command.

Anyway, here’s the final code:
[php]{capture assign=foo}/^[0-9 ]{ldelim}9{rdelim}/{/capture}
{assign var=”shorterThing” value=$thing|regex_replace:$foo:””}[/php]

Of course my match is quite specific, but it worked for what I needed.


Comments

One response to “Emulating PHP’s substr() with Smarty [sort of]”

  1. I suppose you found out by yourself since you wrote this post, but that bit of code is not portable since ldelim and rdelim can be defined to be something else than { and }.

    It’s best to enclose your regex in a {literal} block, so you know you’ll always have curly brackets, regardless of config. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *