I'm looking to replace the last occurrence of P tag in a string.
$bodytext = preg_replace(strrev("/<p>/"),strrev('<p class="last">'),strrev($bodytext),1);
$bodytext = strrev($bodytext);
This works, but can it be done without using strrev? Is there a regex solution?
Something like :
$bodytext = preg_replace('/<p>.?$/', '<p class="last">', $bodytext);
Any help would be greatly appreciated.
My shortened version:
$dom = new DOMDocument();
$dom->loadHTML($bodytext);
$paragraphs = $dom->getElementsByTagName('p');
$last_p = $paragraphs->item($paragraphs->length - 1);
$last_p->setAttribute("class", "last");
$bodytext = $dom->saveHTML();