簡體   English   中英

SIMPLE HTML DOM-如何忽略嵌套元素?

[英]SIMPLE HTML DOM - how to ignore nested elements?

我的html代碼如下

<span class="phone">
i want this text
<span class="ignore-this-one">01234567890</span>
<span class="ignore-this-two" >01234567890</span>
<a class="also-ignore-me">some text</a>
</span>

我要做的是提取“我想要此文本”,而將其他所有元素都保留下來。 我嘗試了以下幾種迭代,但沒有一種返回我需要的文本:

$name = trim($page->find('span[class!=ignore^] a[class!=also^] span[class=phone]',0)->innertext);

由於過濾器的simple_html_dom部分相當裸露,因此將獲得一些指導。

如何使用php preg_match( http://php.net/manual/zh/function.preg-match.php

請嘗試以下方法:

<?php

$html = <<<EOF
<span class="phone">
i want this text
<span class="ignore-this-one">01234567890</span>
<span class="ignore-this-two" >01234567890</span>
<a class="also-ignore-me">some text</a>
</span>;
EOF;

$result = preg_match('#class="phone".*\n(.*)#', $html, $matches);

echo $matches[1];

?>

正則表達式說明:查找文本class =“ phone”,然后繼續進行到行尾,使用*匹配任何字符。 然后使用\\ n切換到新行,並用*括住該行中的所有內容。 放入括號中。

返回的結果存儲在$ matches數組中。 $ matches [0]保留從整個正則表達式返回的值,而$ matches [1]保留由右括號返回的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM