Fill Function

somedude3488 0 Tallied Votes 151 Views Share

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;
}
ShawnCplus 456 Code Monkey Team Colleague

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.

somedude3488 228 Nearly a Posting Virtuoso

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.