Forum Moderators: coopster

Message Too Old, No Replies

Trying to replace the last occurance of a string

Tried numerous things but can't get it to work?!

         

whitenoise

10:46 pm on Sep 4, 2008 (gmt 0)

10+ Year Member Top Contributors Of The Month



Hi everyone,

This is probably a really simple question for you people, but its giving me issues!

I've got a few paragraphs of text that look like:

<p>text text text text text text</p><p>text text text text text text</p><p>text text text</p> .....etc

Now I want to replace each <p> with say <p class="test"> for example. This is fine, so I get:

<p class="test">text text text text text text</p>
<p class="test">text text text text text text</p>
<p class="test">text text text</p>

Now what I want is the last occurance of <p class="test"> changed back to <p>. I'm probably doing this is completely the wrong order or something but I can't get this is work! I've tried strrchr, substr_replace, str_replace etc but nothing - am I missing something really simple or being stupid? :)

Thanks to anyone who can advise!

MattAU

11:51 pm on Sep 4, 2008 (gmt 0)

10+ Year Member



You'll probably need to make use of strrpos (or strpos if you don't use PHP5).

$replace = '<p class="test">';
substr_replace($text, '<p>', strrpos($text,$replace) -1, strlen($replace));

You might need to play with the values a bit, but that should get you close.

whitenoise

10:04 am on Sep 5, 2008 (gmt 0)

10+ Year Member Top Contributors Of The Month



Cheers MattAU! =D Since I use php4 I couldn't exactly use your code, but it put me on the right path of investigation and I've managed to solve it.

Thanks again.