[英]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
用於忽略大小寫匹配 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.