【问题标题】:String between php [duplicate]php之间的字符串[重复]
【发布时间】:2016-09-06 16:06:09
【问题描述】:

我有这样的东西:

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

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

Something written here

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

【问题讨论】:

  • echo strip_tags($string);
  • 仅使用 strip_tags() 可能还会留下一些 &lt;other code&gt;s 的内容...
  • @BlueBockser 没有更详细的问题,我们不知道&lt;some code before&gt; 是否包含将要留下的内容.... 就问题而言,它没有
  • 正如所写, 包含必须删除且未显示的代码。
  • 正如所写,&lt;some code before&gt;&lt;some other code after&gt; 将被 strip_tags() 完全删除....如果 &lt;some other code after&gt; 实际上是 &lt;div&gt;some more text&lt;/div&gt;, then 一些更多的文本将被保留

标签: php string html between


【解决方案1】:

您将使用 DOMDocument 类。

// 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 搜索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 2012-12-14
    相关资源
    最近更新 更多