Jump to content

How would I go about replacing thesecond last instance of something in a string?


rebajas

Recommended Posts

Basically I have several paragraphs of text that make up an article. I'd really like to add a panel between the third and second from last paragraphs offering options such as 'print this page, send to a friend, comment in forum'. Can I do this using preg_replace? I haven't been able to work it out.

 

Regards,

 

 

 

Tony.

Thanks for the quick reply.

 

The data is entered into a form and stored in a mySQL table. When I output to the browser I just run it through nl2br - so I guess initially they are separated by linebreaks? Is there a way to find out for sure?

 

 

Tony.

<?php

$text = "paragraph1\n\nparagraph2\n\nparagraph3"; // Two line breaks in each one

$paragraphs = explode("\n\n", $text); // Split the text into paragraphs

$paragraphs[1] .= "\n\nPrint this page | Send to friend | Comment in forum"; // Add the text to the end of the second paragraph

$text = join("\n\n", $paragraphs); // Join them together again

echo nl2br($text); // Output

?>

 

Output:

 

[pre]paragraph1

 

paragraph2

 

Print this page | Send to friend | Comment in forum

 

paragraph3[/pre]

That looks good - and if I count the items in the array then subtract one then I will always put it in the second from last in the array.

 

I reckon that will solve my problem perfectly - I will do this over the weekend.

 

Thanks,

 

 

Tony.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.