簡體   English   中英

preg匹配html標簽之間的PHP文本

[英]Preg match text in php between html tags

您好我想在PHP中使用preg_match來解析html文檔中的“Desired text”

<p class="review"> Desired text </p>

通常我會使用simple_html_dom這樣的東西,但在這種情況下它不能使用(上面的元素沒有出現在每個所需的div標簽中,所以我被迫使用這種方法來准確跟蹤它何時沒有出現和然后相應地從simple_html_dom調整我的數組)。

無論如何,這將解決我的問題。

非常感謝。

preg_match("'<p class=\"review\">(.*?)</p>'si", $source, $match);
if($match) echo "result=".$match[1];

如果你想返回多個匹配,那么需要使用preg_match_all()。 然后循環遍歷第二個結果組($ match [1])以獲取標記之間的內容。

$source = "<p class=\"review\"> Desired text1 </p>".
"<p class=\"review\"> Desired text2 </p>".
"<p class=\"review\"> Desired text3 </p>";


    preg_match_all("'<p class=\"review\">(.*?)</p>'si", $source, $match);

    foreach($match[1] as $val)
    {
        echo $val."<br>";


    }

Outputs:

Desired text1
Desired text2
Desired text3 

如果您匹配的字符串有多行並且是:

<p class="review"> Desired text1 </p>
<p class="review"> Desired text2 </p>
<p class="review"> Desired text3 </p>

該模式將匹配一次,匹配將是字符串中的所有內容。

我認為更好的模式是:

"'<p class=\"review\">([^<]*)</p>'si"

暫無
暫無

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

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