1

PHP の str_replace、preg_replace などを使用して、特定のクラスを含む非常に長い文字列内のすべての開始 div またはスパンを見つけ、開始 div またはスパン全体を他のテキストに置き換える必要があります。例えば:

文字列に次の div がある場合:

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

文字列全体のクラス名でその div を見つけ、その div を「何とか何とか」に置き換えたいと思います。閉じタグは簡単に見つけられるので気にしません。

ありがとうございました!

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

phpQuery などのツールを使用して、必要な要素を選択し、操作してみてください。

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

正規表現でこれを行うと、不必要に苦痛になります。

于 2013-05-09T00:02:49.587 に答える