Re: Adding text before last paragraph

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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);

Dotan Cohen

http://lyricslist.com/
http://what-is-what.com/

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux