Jump to content

[SOLVED] String Replace but with a difference


willpower

Recommended Posts

Hi

 

Basically I want to use a function like str_replace, except that I only want to replace the 5th occurence of the character to be replaced.

 

Why?

 

Well I have a DB with some shoppiung contents in it.  If any of you have dealt with PROTX card payments you will know that the basked has to be passed in a single $var with a field delimeter of ":"

 

With this single line I want to output this to a txt doc. 

 

I have replaced all ":" with chr(9) (This is the Tab Key) to give me my spacing in the txt doc.  But now I need to create a newline (\n) on every 5th chr(9) (formerly ":")

 

Hope that made sense.

 

Any help appreciated.

 

Will

Looks like you need to write your own str_replace...

$count = 0;
for each $character in $string
{
  if( $character == 9 )
  {
    if( $count == 5 )
    {
      $new .= "\n"
      $count = 0;
    }
    else
    {
      $new .= "\t";
      $count ++;
    }
  }
  else
  {
    $new .= $character;
  }

}

return $new;

 

Any help?

 

monk.e.boy

<pre>
<?php
$numbers = range(1, 100);
$number_string = join(':', $numbers);
function regex_reformat () {
	static $count = 0;
	++$count;
	return $count % 5 ? "\t" : "\n";
}
$new_string = preg_replace_callback('/:/', 'regex_reformat', $number_string);
echo $new_string;
?>
</pre>

Just loop through the string for the characters you are looking for and replace the occurrence...

 

$string = "abcdef:ghijkl:mnop:qrs:tuvw:xyz:ABCD:EFG:HIJKL:MNOPQ:RSTU:VW:XYZ";

$num_found = 0;

for ($i = 0; $i < strlen($string); $i++) {
if ($string{$i} == ":") {
	$num_found++;
	if ($num_found == 5) {
		$string{$i} = "\n";
		$num_found = 0;
	}
}
}

echo $string;

<?php
$numbers = range(1, 100);
$number_string = join(':', $numbers);
function regex_reformat () {
	static $count = 0;
	++$count;
	return $count % 5 ? "\t" : "\n";
}
$new_string = preg_replace_callback('/:/', 'regex_reformat', $number_string);
echo $new_string;
?>

 

That's quite nice  :)

 

monk.e.boy

Effigy

 

I refer to your soloution

 

I just get the numbers 1 to 100 ouputed thru the echo.  May be my fault as I have to say that I dont wholly understand your code.

 

This is what I have


$output="Item1:25:5:--:30:Item2:50:10:00:60:Item3:25:5:--:30";

$numbers = range(1, 100);
$output = join(':', $numbers);

function regex_reformat () {
	static $count = 0;
	++$count;
	return $count % 5 ? "\t" : "\n";
}
$new_string = preg_replace_callback('/:/', 'regex_reformat', $output);
echo $new_string;

 

Where am I going wrong?

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.