php 之间的字符串

String between php

我有这样的东西:

$string = '<some code before><div class="abc">Something written here</div><some other code after>'

我想要的是获取div中的内容并输出:

Something written here

我如何在 php 中做到这一点?提前致谢!

您将使用 DOM文档 class。

// HTML document stored in a string
$html = '<strong><div class="abc">Something written here</div></strong>';

// Load the HTML document
$dom = new DOMDocument();
$dom->loadHTML($html);

// Find div with class 'abc'
$xpath = new DOMXPath($dom);
$result = $xpath->query('//div[@class="abc"]');

// Echo the results...
if($result->length > 0) {
    foreach($result as $node) {
        echo $node->nodeValue,"\n";
    }
} else {
    echo "Empty result set\n";
}

阅读 expression syntax for XPath 以自定义您的 DOM 搜索。