1

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

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

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

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

谢谢!

4

3 回答 3

2

这将替换“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>)|";

于 2013-05-09T00:20:30.253 回答
1

您应该使用 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();
?>
于 2013-05-09T00:05:21.787 回答
1

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.

于 2013-05-09T00:02:49.587 回答