Smarty v.3 preg_match plugin

I wrote a plugin for Smarty which allows to use the php preg_match function inside a template:

Usage:

  1. Copy the plugin in Smarty/plugins/function.preg_match.php
  2. 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;
}

?>

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>