Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

incremental str_replace...help!!

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
hi,
i need some help doing a find and replace on a text string. I want to replace every instance of "%0D%0D" with "&value$i=" within the text string, where $i is a number that increments for each replace.

This is the code I'm using at the moment:

for ($i=0; $i<substr_count($string,&quot;%0D%0D&quot;); $i++)
{
$new_string = str_replace (&quot;%0D%0D&quot;, &quot;&value$i=&quot;, $string);
}

There are 5 instances of &quot;%0D%0D&quot; in the text string. With the above code it does replace all the &quot;%0D%0D&quot;'s to &quot;&value$i=&quot;, but they all read as &quot;&value5=&quot;. But I need them to read: &quot;&value1=&quot; for the first instance of &quot;%OD%OD&quot;, &quot;&value2=&quot; for the second instance of &quot;%OD%OD&quot;, and so on up to &quot;&value5=&quot;.

Any ideas??

thanks,

jc
 
set the count of the strings matched to a different variable cos at the moment you say $i=0 then $i=5 (count of strings matched)

$i=0;
$counter<substr_count($string,&quot;%0D%0D&quot;);
while ($i <= $counter)
{
$new_string = preg_replace(&quot;%0D%0D&quot;, &quot;&value$i=&quot;, $string, 1); // replaces one at a time
$i++;
}
***************************************
Party on, dudes!
 
hi, thanks for the reply. When I try that I get the following error:
Warning: Unknown modifier '0' in / on line 28

line 28 is:
$new_string = preg_replace(&quot;%0D%0D&quot;, &quot;&value$i=&quot;, $string, 1);

any ideas??

thanks again!
 
oh yeah, % is a special character , delimit it with \ and things may look better ;) ***************************************
Party on, dudes!
[cannon]
 
OK after beating my head against the door for a few hours I figured out why it wasn't working for me ...

Note: Parameter limit was added after PHP 4.0.1pl2.

but.. if you have later version then this should work:
$string = preg_replace('/%0D%0D/', &quot;&value$i=&quot;, $string,1); // replaces one at a time ***************************************
Party on, dudes!
[cannon]
 
hey there,
got it working, thanks!
this was the code i used in the end (i'm php v. 4.0.6)
###
$i=1;
$counter=substr_count($s,&quot;%0D%0D&quot;);
while ($i <= $counter)
{
$string = preg_replace('/%0D%0D/', &quot;&value$i=&quot;, $string, 1);
$i++;
}
###

jc
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top