PHP:从包含的数组中删除条目


PHP: Remove entry from array that contains

我从带有file_get_contents的网页中生成一个带有URL的数组,如果它们包含特定数据,我想从中删除条目(键和值)。

例如:

[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:info@somesite.com'

我想删除条目的

http://somesite.com
javascript:void(0)
mailto:info@somesite.com

因为我只需要带有.pdf文件的URL。

我该怎么做?

您可以为此使用数组过滤器(注意,此语法适用于php5.3+)

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

希望这将有所帮助:

$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:info@somesite.com';
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>';
$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:info@somesite.com');
for($i=0; $i<=count($array)+1 ; $i++)
{
    if(end(explode('.',$array[$i])) != "pdf" )
    {
        unset($array[$i]);
    }
}

试试这个!!!!

$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:info@somesite.com'
);
$matches  = preg_grep ('/pdf/i', $haystack);
//print_r ($matches);
foreach($matches as $k=>$v):
    echo $matches[$k]."<br/>";
endforeach;

文档preg_grep

array_filter始终是一个选项,但如果您想删除特定值,另一个好的候选者是array_diff:

$remove = [
    'http://somesite.com',
    'javascript:void(0)',
    'mailto:info@somesite.com',
];
$filtered = array_diff($array, $remove);