2012-09-25 41 views
2

在下面的腳本中我有一個數組。我的數組存儲了網頁中的所有鏈接,標題和描述。但我想確保如果沒有描述,它將使用一個可用的函數使用p標記的前20個字符。唯一的問題是我有拼圖碎片,只是似乎無法將它們放在一起,所以我希望我的if語句顯示如果描述爲空以便使用函數getWord而不是getMetas()我如何使我的函數與我的if語句更改我的數組

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]; 
    } 
    } 
} 

然後,我的功能放在這裏(get_custom_excert),但沒有必要認爲這是我知道的工作。

function getWord() { 
    $html = file_get_contents($link);  
    preg_match('%(<p[^>]*>.*?</p>)%i', $html, $re); 
    $res = get_custom_excerpt($re[1]); 
} 

$outputs = array(); 

foreach ($links as $thisLink) { 
    $output[] = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink)); 

    if ($output['description'] == null) { 
    $output['description'] = getWord($res); 
    } 

    $outputs[] = $output; 
} 

print_r($output); 
+0

對不起,忘了更改我的標題,現在已經完成:) –

+1

正則表達式? HTML?護目鏡......他們什麼都不做! –

回答

0

這是怎麼回事?

foreach ($links as $thisLink) { 
    $output = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink)); 

    if ($output['description'] == null) { 
    $output['description'] = getWord($res); 
    } 

    $outputs[] = $output; 
} 
+1

我在哪裏添加到我的代碼? –

+0

我錯了。你的錯誤是$ output [],它應該是$ output。 – user1122069

0

這是你想要的嗎?

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]; 
    } else { 
     return getWord($str1); 
    } 
    } 
} 

function getWord($html) { 
    preg_match('%(<p[^>]*>.*?</p>)%i', $html, $re); 
    return get_custom_excerpt($re[1]); 
} 

順便說一句,用正則表達式解析HTML是非常脆弱的,最好是使用DOM解析器庫。

相關問題