Smarty v.3 preg_match plugin
January 17, 2012 in php
I wrote a plugin for Smarty which allows to use the php preg_match function inside a template:
Usage:
- Copy the plugin in Smarty/plugins/function.preg_match.php
- In the template use the following code
{$haystack="cow,dog,niddle"}
{if {preg_match pattern="niddle" subject=$haystack}}
{$matches|print_r}
{/if}
Plugin:
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {preg_match} function plugin
*
* Type: function<br>
* Name: preg_match<br>
* Purpose: offers php preg_match function inside a template
* @author Damiano Venturin
* @param array parameters
* @param object $template template object
* @return boolean, matches array in template
*/
function smarty_function_preg_match($params, $template)
{
$flags = (empty($params['flags']) ? 0 : $params['flags']);
$offset = (empty($params['offset']) ? 0 : $params['offset']);
$match = preg_match("/".$params['pattern']."/", $params['subject'], $matches, $flags, $offset);
$template->assign('matches', $matches);
return $match;
}
?>