Ton*_*tra 3 html php regex curl preg-replace
我想从海盗湾获取统计数据,统计数据可以在TPB的以下div中找到:
<div id="stats">5.695.184 registered users Last updated 14:46:05.<br />35.339.741 peers (25.796.820 seeders + 9.542.921 leechers) in 4.549.473 torrents.<br /> </div>
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
<?php
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL,"http://thepiratebay.se");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
curl_setopt($ch,CURLOPT_COOKIE,"language=nl_NL; c[thepiratebay.se][/][language]=nl_NL");
$data=curl_exec($ch);
$data = preg_replace('/(.*?)(<div id="stats">)(.*?)(<\/div>)(.*?)/','$2',$data);
echo $data;
curl_close($ch);
exit;
?>
Run Code Online (Sandbox Code Playgroud)
如您所见,我使用以下preg-replace模式来剥离HTML:
$data = preg_replace('/(.*?)(<div id="stats">)(.*?)(<\/div>)(.*?)/','$2',$data);
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我得到了TPB的整个页面而不仅仅是统计数据.有人有答案吗?
提前致谢.
忘记使用正则表达式进行屏幕报废,使用domDocument,看看它有多简单:
<?php
function curl_get($url){
$useragent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch,CURLOPT_COOKIE,"language=nl_NL; c[thepiratebay.se][/][language]=nl_NL");
$data=curl_exec($ch);
curl_close($ch);
return $data;
}
function get_pb_stats(){
$html = curl_get("http://thepiratebay.se");
// Create a new DOM Document
$xml = new DOMDocument();
// Load the html contents into the DOM
@$xml->loadHTML($html);
$return = trim($xml->getElementById('stats')->nodeValue);
//regex to add the brake tag after 15:04:05.
$return = preg_replace('/\d{2}[:]\d{2}[:]\d{2}[.]/','${0}<br />',$return);
return $return;
}
echo get_pb_stats();
/*
5.695.213 geregistreerde gebruikers Laatste update 15:04:05.<br />35.505.322 peers (25.948.185 seeders + 9.557.137 leechers) in 4.546.560 torrents.
*/
?>
Run Code Online (Sandbox Code Playgroud)