Question

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();
Was it helpful?

Solution

Some people will complain that DOMDocument is more verbose for parsing HTML then a regex. But verbosity is okay if it means using the right tool for the job.

$previous_value = libxml_use_internal_errors(TRUE);
$string = '<p>hi, mom</p><p>bye, mom</p>';
$dom = new DOMDocument();
$dom->loadHTML($string);
$paragraphs = $dom->getElementsByTagName('p');
$last_p = $paragraphs->item($paragraphs->length - 1);
$last_p->setAttribute("class", "last");
$new_string = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
libxml_clear_errors();
libxml_use_internal_errors($previous_value);

echo htmlentities($new_string);
// <p>hi, mom</p><p class="last">bye, mom</p>

See it in action

OTHER TIPS

How about using simple html dom?

require_once('simple_html_dom.php');

$string = '<p>hi, mom</p><p>bye, mom</p>';
$doc = str_get_html($string);
$doc->find('p', -1)->class = 'last';
echo $doc;
// <p>hi, mom</p><p class="last">bye, mom</p>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top