PHP按类替换开始div或span

时间:2013-05-08 23:42:48

标签: php replace preg-replace

使用类似PHP的str_replace,preg_replace或其他东西,我需要在一个包含某个类的非常长的字符串中找到所有打开的div或spans,并用一些其他文本替换整个开头div或span。例如:

如果我的字符串中有以下div:

...lots of text <div style="display: inline;" class="MyClass">zoom</div> other text...

我想通过整个字符串中的类名找到div,并用“blah blah blah”替换该div。我可以轻松找到结束标签,所以我不担心那个。

谢谢!

3 个答案:

答案 0 :(得分:1)

这将替换“MyClass”div标签之间的所有文本,并将新HTML存储在$ 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>

?>

要替换包括div标签在内的所有内容,正则表达式模式将为$pattern = "|(<div class=\"MyClass\">.*?<\/div>)|";

答案 1 :(得分:0)

尝试使用像phpQuery这样的工具来选择你想要的元素,然后对它们进行操作。

http://code.google.com/p/phpquery/

使用正则表达式执行此操作会产生不必要的痛苦。

答案 2 :(得分:0)

您应该使用DOMDocument。使用正则表达式会使事情变得复杂。请参阅下面的示例代码,了解如何实现此目标。

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