2014-10-01 94 views
-2

我該如何輸出123456654321如何preg_match php html標籤?

這是html代碼:

<div class="nb"><i class="id"></i>123456</div> 
<div class="nb"><i class="id"></i>654321</div> 
<div>another dummy text</div> 

我想下面這段代碼,但是從123456到這一切只能輸出。

preg_match("~<i class=\"id\"></i>(.*)</div>~", $var, $A); 
print $A[1]; 
+3

你的正則表達式會變得不必要的複雜。有沒有理由不能使用像[Simple HTML DOM](http://simplehtmldom.sourceforge.net/)這樣的庫? – wavemode 2014-10-01 12:33:59

+0

即時通訊對不起,我不知道簡單的HTML DOM使用。任何運行在PHP上的東西都可以。我只想輸出123456和654321 – 2014-10-01 12:35:36

+3

@ChamindaNuwan - 所以學習它。 – Quentin 2014-10-01 12:36:04

回答

0

我想你需要

preg_match_all

的模式應該是這樣的:

'<div class="nb"><i class="id"></i>([0-9]+)</div>' 
1

我建議你使用一個HTML解析器爲了這個目的,其實我想推薦使用DOMDocument而不是simple-html-dom,因爲DOMDocument已經內置,所以不需要另外導入庫。

在這個例子中,針對那些<i>標籤,並指向那些下一個兄弟是文本:

$dom = new DOMDocument(); 
libxml_use_internal_errors(true); 
$dom->loadHTML($string); 
libxml_clear_errors(); 

echo '<br/>'; 
foreach($dom->getElementsByTagName('i') as $i) { 
    echo $i->nextSibling->textContent . '<br/>'; 
} 

那麼,這樣做其實是針對這些:

<i class="id"></i>123456 
^^ this element, and then inside the loop get the next sibling which is the `123456` 
0

試試這個

<?php 

$source='<div class="nb"><i class="id"></i>123456</div> 
<div class="nb"><i class="id"></i>654321</div>'; 
    preg_match_all("'<div class=\"nb\"><i class=\"id\"></i>(.*?)</div>'", $source, $match); 
print_r($match); 
foreach($match[1] as $val) 
    { 
     echo $val."<br>"; 
    } 

?> 

它對我有用