Smarty Plugin – Between

Oct 11, 10 • SmartyNo CommentsRead More »

This is a nice little plugin for smarty that allows you to return a portion of a large string between two strings. Sound confusing? Let me explain. Say you had a string in bold tags; you could use this function to essentially strip out those bold tags. Below are some examples:

Strip out bold tags:
{$my_string|between:’<b>’:'</b>’}

Format currency ( $99.00 => $99 )
{$my_string|betewen:0:’.'}

Only grab first name ( ‘Alex Roxon’ => ‘Alex’ )
{$my_string|between:0:’ ‘}

Place the file in your Smarty plugin folder (mine is lib/smarty/plugins) and name it modifier.between.php:

<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */


/**
 * Smarty between modifier plugin
 *
 * Type:     modifier<br>
 * Name:     between<br>
 * Purpose:  return a string between two strings (or integer positions)
 * Example 1 (return text inside bold tags):
 *		{$my_string|between:'<b>':'</b>'}
 * Example 2 (return text inside two integer positions):
 *		{$my_string|between:10:20}
 * @author   Alex Roxon <alex at ajberri dot com>
 * @param string
 * @param boolean
 * @return string
 */
function smarty_modifier_between($string, $start = 0, $end = 1)
{
	// Retrieve the start and end position
    $startPos = ( is_string( $start ) ) ? strpos( $string, $start ) + strlen( $start ) : $start;
	$endPos = ( is_string( $end ) ) ? strpos( $string, $end ) : $end;
	
	// Return the correct value
	return substr( $string, $startPos, $endPos );

}

/* vim: set expandtab: */

?>

Tags: , , , ,

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>