Reputation: 1665
Using something like PHP's str_replace, preg_replace, or something else, I need to find all opening div or spans in a very long string that contain a certain class and replace the entire opening div or span with some other text. For example:
If I have the following div in my string:
...lots of text <div style="display: inline;" class="MyClass">zoom</div> other text...
I want to find that div by the class name in the entire string and replace that div with "blah blah blah." I can find the closing tag easily so I'm not worried about that one.
Thank you!
Upvotes: 1
Views: 4224
Reputation: 1835
This replaces all the text between "MyClass" div tags and stores the new HTML in $string.
<?php
$string = '<div class="MyClass">Change this text.</div><br /><div class="MyClass">and this text too</div>';
$pattern = "|(?<=<div class=\"MyClass\">)(.*?)(?=<\/div>)|";
$replace = 'blah blah blah';
$matches = array();
preg_match_all($pattern, $string, $matches);
foreach ($matches[0] as $value) {
$string = str_replace($value, $replace, $string);
}
echo $string; // <div class="MyClass">blah blah blah</div><br /><div class="MyClass">blah blah blah</div>
?>
To replace everything including the div tags, the regex pattern would be $pattern = "|(<div class=\"MyClass\">.*?<\/div>)|";
Upvotes: 2
Reputation: 4014
You should use DOMDocument. Using regular expression will over complicate things. See my sample code below on how you would accomplish this.
<?php
// This is our HTML
$html = <<<HTML
<html>
<body>
...lots of text <div style="display: inline;" class="MyClass">zoom</div> other text...
</body>
</html>
HTML;
// This is the replacement.
$replacement = <<<HTML
Blah blah blah
HTML;
// Create a new DOMDocument with our HTML.
$document = new DOMDocument;
$document->loadHtml($html);
// Create a new DOMDocument with the replacement text.
$replacementDocument = new DOMDocument;
$replacementDocument->loadXml('<root>' . $replacement . '</root>');
// Import the nodes from the replacement document into the existing document.
$newNodes = array();
foreach($replacementDocument->firstChild->childNodes as $childNode){
$newNodes[] = $document->importNode($childNode,true);
}
// Create an xpath use for querying.
$xpath = new DOMXpath($document);
// Find all nodes that have a class with "MyClass"
foreach($xpath->query('//*[contains(@class,\'MyClass\')]') as $element){
// Remove all the nodes inside this node.
foreach($element->childNodes as $childNode){
$element->removeChild($childNode);
}
// All all the new nodes.
foreach($newNodes as $newNode){
$element->appendChild($newNode);
}
}
// Echo the new HTML
echo $document->saveHtml();
?>
Upvotes: 1
Reputation:
Try using a tool like phpQuery to select the elements you want and then manipulate them.
http://code.google.com/p/phpquery/
Doing this with regular expressions would be unnecessarily painful.
Upvotes: 1