0

我从带有 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。

我怎么做?

4

5 回答 5

2

您可以为此使用数组过滤器(注意此语法适用于 php 5.3+)

$filtered = array_filter($array, function ($a){ return preg_match ('/.pdf$/', $a); });
于 2013-07-12T16:10:49.663 回答
1

希望这会有所帮助:

$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>';
于 2013-07-12T17:34:21.903 回答
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:info@somesite.com');

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

}
于 2013-07-12T17:02:45.570 回答
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:info@somesite.com'
);

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

//print_r ($matches);

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

文档 preg_grep

于 2013-07-12T17:16:43.610 回答
0

array_filter is always an option, but if you want to remove specific values another good candidate is array_diff:

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

$filtered = array_diff($array, $remove);
于 2013-07-12T17:49:09.860 回答