0

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;
}
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by somedude3488
0

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.

0

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.

Edited by somedude3488: n/a

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.