This was not obvious to me nor apparently anyone else trying to use preg_match in Smarty so I thought I’d share the solution. Given $href=’home.php?cat=1′ and trying to get 1 out of it:
{if "/cat=(\d+)/"|preg_match:$href:$match} {$href = "My-Page-`$match.1`.html"} {/if}
preg_match returns the number of times it matched so we can use it directly as our condition then it dumps all of the matches into the $match array which looks like this:
[0] => cat=1 [1] => 1
The key is that you can pass all of the parameters separated by colon (:) as mentioned in the Smarty docs:
parameters follow the modifier name and are separated by a : (colon)
But that’s as far as the docs go and they don’t provide examples of more advanced PHP functions with multiple parameters, especially those who use a parameter as a return variable. Even the admins of the Smarty forums only pointed to creating a plugin, probably because they feel you should be doing this at a higher level instead of in Smarty, which is a fair point.
This was originally done with an old version of Smarty which also works except for the condition shortcut but this may also help spell it out a little:
{assign var='matched' value="/cat=(.+)/"|preg_match:$href:$match} {if $matched} {assign var='href' value="My-Page-`$match.1`.html"} {/if}
You can also use PHP functions in Smarty like the following, but $match did not have our matching array when working with the old version of Smarty but it does work with Smarty 3:
{if preg_match("/cat=(.+)/", $href, $match)}
If you are dealing with a greedy match, you can also use preg_match_all. If I had been working with a newer version of Smarty my initial try with this last method would have worked and I may have stopped there but hopefully this exercise helps someone.
Leave a Reply
You must be logged in to post a comment.