簡體   English   中英

使用PHP中的正則表達式匹配兩個HTML標記之間的所有文本

[英]Match all text between two HTML tags using a regex in PHP

我有一個正則表達式模式的問題。 它返回兩個數組...這是我的代碼:

$code = preg_match_all("/\< style\>(.*?)\<\/style\>/",$code,$matches);
var_dump($matches);

作為測試我設置:

$code = ">< xxxxx> try blah fooo blah   < /xxxxx> idfidf oh < x>< /x> < style> blah blah blah style1 < /style>< style>blah blah style 2 x< /style>

我的意思是它返回2個數組

$matches = array
    0 => array
        0 => string '< style> blah blah blah style1 < /style>' (length=38)
        1 => string '< style>blah blah style 2 x< /style>' (length=34)
    1 => array
        0 => string ' blah blah blah style1 ' (length=23)
        1 => string 'blah blah style 2 x' (length=19)

我想要的匹配在第二個數組中。 我在標簽之間放置了空格,因為編輯器沒有顯示HTML標簽。

你試過這個:

echo $matches[0];
echo $matches[1]; // and so on, depend in the number of matches.

以下代碼對我有用:

$code = "<xxxxx> try blah fooo blah </xxxxx> idfidf oh <x></x> <style> blah blah blah style1 </style><style>blah blah style 2 x</style>";
$code = preg_match_all("~<style>(.*?)</style>~si", $code, $matches);
var_dump($matches[1]);
  • 改性劑s為DOT_ALL(包括換行)
  • 修飾符i用於忽略大小寫匹配

OUTPUT

array(2) {
  [0]=>
  string(23) " blah blah blah style1 "
  [1]=>
  string(19) "blah blah style 2 x"
}

但是,只是為了讓您知道從正則表達式解析HTML不是一個好主意,您最好使用許多可用於PHP的HTML解析器。

使用Xpath怎么樣? http://nl.php.net/manual/en/class.domxpath.php

對我有用(大多數時候,就是;))

暫無
暫無

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

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