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

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

Reply via email to