正確的我已經建立了一個網絡爬蟲。它掃描鏈接,標題和元描述。它掃描鏈接並將它們保存在$ link中。它掃描鏈接的標題並將它們保存在newArray的[標題]中。現在在這個數組中,我想知道如果沒有元標籤,它可以掃描第一個p標籤並使用它。唯一的問題是,它似乎並沒有保存任何信息。如何使用20個字符的p標籤如果沒有元描述
function getMetas($link) {
$str1 = file_get_contents($link);
if (strlen($str1)>0) {
preg_match_all('/<meta.*?name=("|\')description("|\').*?content=("|\')(.*?)("|\')/i', $str1, $description);
if (count($description) > 1) {
return $description[4];
}
}
return '';
if ($description == '') {
$html = file_get_contents($link);
preg_match('%(<p[^>]*>.*?</p>)%i', $html, $re);
$res = get_custom_excerpt($re[1]);
echo "\n";
echo $res;
echo "\n";
}
function get_custom_excerpt($return, $option = 30, $sentance = false) {
$marks = Array(".","!","?");
$return = strip_tags($return);
if($sentance == true) {
$start = implode(" ", array_slice(preg_split("/\s+/", $return), 0, $option));
$start .= ' ';
$end = implode(" ", array_slice(preg_split("/\s+/", $return), $option));
$cut = Array();
foreach($marks AS $m => $mark){
$mark = strpos($end, $mark);
if($mark != false) $cut[$m] = $mark;
}
if($cut[0] != "")
$chop = min($cut);
else
$chop = $option;
$rest = substr($end, 0, $chop);
$key = array_search($chop, $cut);
$return = $start.$rest;
}else{
$return = implode(" ", array_slice(preg_split("/\s+/", $return), 0, $option));
}
$return .= $marks[$key];
return $return;
}
}
$output = Array();
foreach ($links as $thisLink) {
$output[] = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink), getMetas($res));
}
print_r($output);
我會建議使用XPath來選擇的元素和內容,而不是正則表達式。 – str