2013-07-12 42 views
0

我使用file_get_contents從網頁生成一個數組,其中包含file_get_contents,如果它們包含特定數據,我想刪除條目的(值爲&)值。PHP:從陣列中刪除條目,其中包含

例如:

[0] = 'http://somesite.com' 
[1] = 'http://someothersite.com/article/id/55/file.pdf' 
[2] = 'http://someothersite.com/article/id/56/file2.pdf' 
[3] = 'javascript:void(0)' 
[4] = 'mailto:[email protected]' 

我想刪除該條目

http://somesite.com 
javascript:void(0) 
mailto:[email protected] 

因爲我只需要在URL的與.pdf文件。

我該怎麼做?

+0

那麼,爲什麼你不修改你的初始uri獵犬? – dead

回答

2

您可以使用濾鏡陣列此(注意,PHP這個語法作品5.3+)

$filtered = array_filter($array, function ($a){ return preg_match ('/.pdf$/', $a); }); 
+0

@downvoter更新中...現在作品:) – Orangepill

0
$array = array('http://somesite.com','http://someothersite.com/article/id/55/file.pdf','http://someothersite.com/article/id/56/file2.pdf','javascript:void(0)','mailto:[email protected]'); 

for($i=0; $i<=count($array)+1 ; $i++) 
{ 
    if(end(explode('.',$array[$i])) != "pdf") 
    { 
     unset($array[$i]); 
    } 

} 
0

試試這個!!!!

$haystack = array (
'0' => 'http://somesite.com', 
'1' => 'http://someothersite.com/article/id/55/file.pdf', 
'2' => 'http://someothersite.com/article/id/56/file2.pdf', 
'3' => 'javascript:void(0)', 
'4' => 'mailto:[email protected]' 
); 

$matches = preg_grep ('/pdf/i', $haystack); 

//print_r ($matches); 

foreach($matches as $k=>$v): 
    echo $matches[$k]."<br/>"; 
endforeach; 

文檔 preg_grep

0

希望這將有助於:

$sites[0] = 'http://somesite.com'; 
$sites[1] = 'http://someothersite.com/article/id/55/file.pdf'; 
$sites[2] = 'http://someothersite.com/article/id/56/file2.pdf'; 
$sites[3] = 'javascript:void(0)'; 
$sites[4] = 'mailto:[email protected]'; 

echo '<pre>'.print_r($sites, true).'</pre>'; 

//loop through your array of items/sites 
foreach($sites as $key=>$value){ 
    //remove whitespace 
    $value = trim($value); 

    //get last 4 chars of value 
    $ext = substr($value, -4, 0); 

    //check if it is not .pdf 
    if($ext != '.pdf'){ 
     //unset item from array 
     unset($sites[$key]); 
    } 
} 

echo '<pre>'.print_r($sites, true).'</pre>'; 
0

array_filter始終是一個選擇,但如果你想刪除特定的值,另一個很好的選擇是array_diff

$remove = [ 
    'http://somesite.com', 
    'javascript:void(0)', 
    'mailto:[email protected]', 
]; 

$filtered = array_diff($array, $remove);