Forum Moderators: coopster

Message Too Old, No Replies

Find/Replace the third instance in a string

         

internetheaven

7:08 pm on Jul 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Been struggling to find this. I have a string with several occurences of <br><br><br>. I want to replace the third occurrence of "<br><br><br>" with "</td><td align="right">" but can't find the right command. I've tried every variation of str... available I think. Am I looking in the wrong place?

Thanks
Mike

nick279

7:40 pm on Jul 26, 2008 (gmt 0)

10+ Year Member



bit unorthadox, but how about

str_replace("<br><br><br>","<br><br></td><td align=\"right\">",$string);

internetheaven

7:53 pm on Jul 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That changes EVERY occurrence of <br><br><br> in the string.

(and what was the unorthadox part?)

janharders

7:57 pm on Jul 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



hm, you could do it with stripos, basically just search for <br><br><br>, repeat with offset, repeat again. then you know, where exactly the brs you want to replace are. the rest should be simply
substr($string, 0, x) . '</td><td align="right">' . substr($string, x + 12)

internetheaven

8:31 pm on Jul 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Tried and it ended up crashing the script before I even got to the offset part (which I know nothing about!).

Late here though, I'll try again with fresh eyes.

janharders

8:47 pm on Jul 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I was thinking something along the lines of
<?
$string = 'aaa <br><br><br> bbb <br><br><br> ccc <br><br><br> ddd <br>';
$pos1 = strpos($string, '<br><br><br>');
$pos2 = strpos($string, '<br><br><br>', $pos1 + 12);
$pos3 = strpos($string, '<br><br><br>', $pos2 + 12);
if($pos3)
{
$string2 = substr($string, 0, $pos3) . '</td><td align="right">' . substr($string, $pos3+12);
}

?>

had only php4 available on local testserver (don't really use php), so strpos instead of stripos. it's not a beauty, but it should get the job done.

internetheaven

7:12 pm on Jul 27, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That worked perfectly! Thanks very much.