subrion icon indicating copy to clipboard operation
subrion copied to clipboard

String formatting issues

Open nkanaev opened this issue 7 years ago • 1 comments

Hi,

Both bind and printf functions in iaDb implementations have the same issue when trying to format a string. For ex:

iaDb::printf("item = :item and item_id = :item_id", array("item" => "foo", "item_id" => "bar"));

What I'm expecting:

"item = foo and item_id = bar"

What I get:

"item = foo and item_id = foo_id"

Currently to solve the issue I have to create replacement array in a way where overlapped keys are declared before.

It would be nice to fix it. I believe that reverse sorting keys (inside a function) might solve the issue. At least it will eliminate overlapping replacement where one key is the prefix of another.

nkanaev avatar Nov 25 '16 04:11 nkanaev

More generalized solution to string formatting might look like this:

<?php

function format($str, $data)
{
	$chunks = preg_split("/(:\w+)/", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
	$output = '';
	foreach ($chunks as $chunk)
	{
		if ($chunk[0] == ':')
			$output .= $data[substr($chunk, 1)];
		else
			$output .= $chunk;
	}
	return $output;
}

// output: "test foo bar"
echo format("test :item :item_id", array('item' => 'foo', 'item_id' => 'bar'));

nkanaev avatar Nov 28 '16 04:11 nkanaev