Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.