Emulating PHP's substr() with Smarty [sort of]
Posted in Development, php on September 7, 2006
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
(http://uk.php.net) functions as modifiers so I could not simply do `$string=[substr](http://uk2.php.net/manual/en/function.substr.php)($string,9);` or even {[assign](http://smarty.php.net/manual/en/language.custom.functions.php#language.function.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}](http://smarty.php.net/manual/en/language.builtin.functions.php#language.function.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:""}
Of course my match is quite specific, but it worked for what I needed.