954,561 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Fill Function

0
By Kyle Keith on Sep 15th, 2009 2:33 am

Got bored and made a function that handles filling strings similar to mysqli bind_param. It actually gets used a lot in my code. Figured someone else might find it useful.

Example usage:
Using question marks as place holders

$str = 'Hello, my daniweb user name is ? and my real name is ?';
echo fill( $str,'kkeith29','Kyle Keith' );


Using named place holders

$str = 'Hello, my daniweb user name is :user-name and my real name is :real-name';
echo fill( $str,array('user-name'=>'kkeith29','real-name'=>'Kyle Keith') );


Mixing question mark and named place holders

$str = 'Hello, my daniweb user name is ? and my real name is :real-name';
echo fill( $str,'kkeith29',array('real-name'=>'Kyle Keith') );


Escaping place holders - Just put a \ in front

$str = 'Hello, my daniweb user name is \? and my real name is \:real-name';
echo fill( $str,'kkeith29',array('real-name'=>'Kyle Keith') ); //won't replace anything.
function fill() {
	$args = func_get_args();
	$str = array_shift( $args );
	foreach( $args as $arg ) {
		if ( is_array( $arg ) ) {
			foreach( $arg as $part => $data ) {
				while( false !== ( $pos = strpos( $str,":{$part}" ) ) && substr( $str,( $pos - 1 ),1 ) !== '\\' ) {
					$str = substr_replace( $str,$data,$pos,( strlen( $part ) + 1 ) );
				}
			}
			continue;
		}
		if ( false !== ( $pos = strpos( $str,'?' ) ) && substr( $str,( $pos - 1 ),1 ) !== '\\' ) {
			$str = substr_replace( $str,$arg,$pos,1 );
		}
	}
	return $str;
}

Hmm, have you seen sprintf or does this serve a different purpose? This could be great if the function took, say, a callback function that could be used to validate fields that were passed to it.

ShawnCplus
Code Monkey
Team Colleague
1,583 posts since Apr 2005
Reputation Points: 526
Solved Threads: 268
 

I use sprintf occasionally. I just liked throwing a ? wherever I need something. Not saying %s is hard or anything. I don't need to worry about data type conversion because I handle that in my code.

Also it allows for using the same data more than once. If I use :user-name more than once in a string, all the placeholders will be replaced. With sprintf I would have to add the username as a param twice.

The callback is a great idea, but I have no idea how I would integrate it. As of right now, I don't see a way of adding it and not overcomplicating the function.

kkeith29
Nearly a Posting Virtuoso
1,357 posts since Jun 2007
Reputation Points: 235
Solved Threads: 194
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You