Adding text before last paragraph
| From: | Dotan Cohen | Date: | Sun, 26 Aug 2007 20:41:40 +0000 |
| Subject: | Adding text before last paragraph | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-261302@lists.php.net to get a copy of this message | ||
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.
Dotan Cohen
http://lyricslist.com/
http://what-is-what.com/