0

Possible Duplicate:
get wrapping element using preg_match php

I want to get the element that wraps a specified string, so example:

$string = "My String";
$code = "<div class="string"><p class='text'>My String</p></div>";

So how am i able to get <p class='text'></p> that wraps the string by matching it using regex pattern.

Community
  • 1
  • 1
PHP Noob
  • 1,597
  • 3
  • 24
  • 34

1 Answers1

0

Using the DOM Classes of PHP you are able to do so.

$html = new DomDocument();
// load in the HTML
$html->loadHTML('<div class="string"><p class=\'text\'>My String</p></div>');
// create XPath object
$xpath = new DOMXPath($html);
// get a DOMNodeList containing every DOMNode which has the text 'My String'
$list = $xpath->evaluate("//*[text() = 'My String']");
// lets grab the first item from the list
$element = $list->item(0);

now we have the whole <p>-tag. But we need to remove all child nodes. Here a little function:

function remove_children($node) {
  while (($childnode = $node->firstChild) != null) {
    remove_children($childnode);
    $node->removeChild($childnode);
  }
}

let's use this function:

// remove all the child nodes (including the text 'My String')
remove_children($element);

// this will output '<p class="text"></p>'
echo $html->saveHTML($element);
MarcDefiant
  • 6,649
  • 6
  • 29
  • 49