On Mon, August 27, 2007 1:46 am, Dotan Cohen wrote: > On 27/08/07, Richard Lynch <ceo@xxxxxxxxx> wrote: >> On Sun, August 26, 2007 3:41 pm, Dotan Cohen wrote: >> > I have a string with some HTML paragraphs, like so: >> > $text="<p>First paragraph</p>\n<p>More text</p>\n<p>Some more >> > text</p>\n<p>End of story</p>"; >> > >> > I'd like to add an image before the last paragraph. I know that >> > preg_replace can replace only the first n occurrences of a string, >> but >> > how can I replace the _last_ occurrence of a string? My initial >> idea >> > was to do this: >> > 1) Count how many times "</p>\n<p>" occurs as $n >> > 2) Replace them all with "</p>\n<img src= alt=>\n<p>" >> > 3) Replace $n-1 replacements back to "</p>\n<p>" >> > >> > Is there a cleaner way? Thanks in advance. >> >> If the string really really ENDS on that LAST "</p>", then you can >> key >> off of that: >> >> $story = preg_replace("|(<p>.*</p>\$|Umsi", >> "<p>$new_paragraph</p>\n\\1", $story; >> >> You may have to fiddle with the DOT_ALL setting to only match the >> true >> end of string and not just any old "\n" within the string... >> http://php.net/pcre >> > > Thanks, Richard, I was also trying to use a regex with pre_replace and > getting nowhere. In the manual page for strrpos, there is a > user-comment function for finding the last occurrence of a string: > http://il2.php.net/manual/en/function.strrpos.php#56735 > > However, I am unable to piece 2 and 2 together. > > Note that I'm adding a paragraph before the last paragraph, so I'm > searching for the last instance of "</p>\n<p>". > > This is what I've done to your code, but I'm unable to get much > further: > $text = preg_replace("|(</p>\n<p>)\$|Umsi", "</p>\n<p>Test</p>\n<p>", > $text); The strrpos solution might be better/easier... $last_paragraph = strrpos($text, "</p>\n<p>"); $text = substr($text, 0, $last_paragraph - 1) . "</p>\n<p>Test" . substr($text, $last_paragraph); I almost always get the "- 1" bit in the wrong place, but that should get you close enough to work it out. -- Some people have a "gift" link here. Know what I want? I want you to buy a CD from some indie artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php