匹配網頁內容的網址的正則
我希望把這個網址http://www.425sf.com/的網址都匹配出來
PHP code
$url = "http://www.425sf.com/";//採集地址$content = file_get_contents($url);$patten = "^((https|http|ftp|rtsp|mms)?://)?(([0-9a-z_!~*'().&=+$%-]+:)?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";preg_match_all($patten, $content, $matches);
上面的匹配正則我是參考這裡的
http://topic.csdn.net/u/20070307/14/87e6b878-800e-4a88-830e-7d0eeeaba891.html
我用正則測試載入器試過比較準確
但是這裡php運行好像取不出來
------解決方案--------------------
PHP code
$html = << http://www.baidu.com [1] => http://hi.baidu.com?info=aaa)*/
------解決方案--------------------
LS正解:
preg_match_all
(PHP 4, PHP 5)
preg_match_all ― 進行全域Regex匹配
說明
int preg_match_all ( string $pattern , string $subject , array $matches [, int $flags ] )
在 subject 中搜尋所有與 pattern 給出的Regex匹配的內容並將結果以 flags 指定的順序放到 matches 中。
搜尋到第一個匹配項之後,接下來的搜尋從上一個匹配項末尾開始。
flags 可以是下列標記的組合(注意把 PREG_PATTERN_ORDER 和 PREG_SET_ORDER 合起來用沒有意義):
PREG_PATTERN_ORDER
對結果排序使 $matches[0] 為全部模式比對的數組,$matches[1] 為第一個括弧中的子模式所匹配的字串組成的數組,以此類推。
preg_match_all ("|<[^>]+>(.*)]+>|U",
"example: this is a test",
$out, PREG_PATTERN_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n";
?>
本例將輸出:
example: , this is a test
example: , this is a test
因此,$out[0] 包含匹配整個模式的字串,$out[1] 包含一對 HTML 標籤之間的字串。
PREG_SET_ORDER
對結果排序使 $matches[0] 為第一組匹配項的數組,$matches[1] 為第二組匹配項的數組,以此類推。
preg_match_all ("|<[^>]+>(.*)]+>|U",
"example: this is a test",
$out, PREG_SET_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n";
?>
本例將輸出:
example: , example:
this is a test, this is a test
本例中,$matches[0] 是第一組匹配結果,$matches[0][0] 包含匹配整個模式的文本,$matches[0][1] 包含匹配第一個子模式的文本,以此類推。同樣,$matches[1] 是第二組匹配結果,等等。
PREG_OFFSET_CAPTURE
如果設定本標記,對每個出現的匹配結果也同時返回其附屬的字串位移量。注意這改變了返回的數組的值,使其中的每個單元也是一個數組,其中第一項為匹配字串,第二項為其在 subject 中的位移量。本標記自 PHP 4.3.0 起可用。
如果沒有給出標記,則假定為 PREG_PATTERN_ORDER。
返回整個模式比對的次數(可能為零),如果出錯返回 FALSE。
Example #1 從某文本中取得所有的電話號碼
preg_match_all ("/\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x",
"Call 555-1212 or 1-800-555-1212", $phones);
?>
Example #2 搜尋匹配的 HTML 標籤(greedy)
// \\2 是一個逆向引用的例子,其在 PCRE 中的含義是
// 必須匹配Regex本身中第二組括弧內的內容,本例中
// 就是 ([\w]+)。因為字串在雙引號中,所以需要
// 多加一個反斜線。
$html = "bold textclick me";