PHP Function to Apply Multiple Others...

From time to time I'll post little snippets of code that I have been asked for, or see requested again and again. One such request is the ability to apply a set of transformations to text (or whatever) again and again without writing them out each time.

Imagine you have a set of user comments at various places on your site. Assume that you wish to apply three functions to them, but that you are not (for whatever reason) looping over them (i.e. they are separated). You could do something like this: (strings rather than variables used for clarity)

echo '<p>'.ucfirst(wordwrap(trim(' this is my first string as it may appear from the database ', "/\\ \n\r\t"), 30, '<br />', false)).'</p>';
# Whatever else here
echo '<p>'.ucfirst(wordwrap(trim(' / this is my second string as it may appear from the database \\ ', "/\\ \n\r\t"), 30, '<br />', false)).'</p>';
# Whatever else here
echo '<p>'.ucfirst(wordwrap(trim('    you get the concept / idea...', "/\\ \n\r\t"), 30, '<br />', false)).'</p>';

Which is a pain to keep on writing and not clear at a glance. You could write a custom function for this scenario, but if you do thins kind of thing a lot (I don't but nevermind) you could write a general function for the purpose. So the aim is:

$options = array(	'trim'		=> array("/\\ \n\r\t"), 
					'wordwrap'	=> array(30, '<br />', false), 
					'ucfirst' 
				);
 
echo '<p>'.transform(' this is my first string as it may appear from the database ', $options).'</p>';
# Whatever else here
echo '<p>'.transform(' / this is my second string as it may appear from the database \\ ', $options).'</p>';
# Whatever else here
echo '<p>'.transform('    you get the concept / idea...', $options, 'trim, wordwrap, ucfirst - useful if you cannot see the options array').'</p>';

And the output for both should be:

<p>This is my first string as it<br />may appear from the database</p>
<p>This is my second string as it<br />may appear from the database</p>
<p>You get the concept / idea...</p>

The very basic tranform function (below) uses the useful 'call_user_func_array' function to trigger your declared function calls. The functions can be existing PHP functions or your own ones.

# Description does nothing, but allows you to write a note
function transform($string, $options, $description)
{
	if(is_array($options))
	{
		foreach($options as $function => $arguments)
		{
			if(!is_array($arguments))
			{
				$function	= $arguments;
				$parameters = $string;
			}
			else
			{
				$parameters = array();
				$parameters[] = $string;
 
				foreach($arguments as $argument)
				{
					$parameters[] = $argument;
				}
			}
 
			$string = call_user_func_array($function, $parameters);
		}
	}
	else
	{
		$string = call_user_func($options, $string);
	}
 
	return $string;
}

Hope some people find it useful - I know one person did!