取消设置与模式匹配的数组项

时间:2012-02-25 13:32:06

标签: php arrays

我有以下数组:

Array
{
    [0]=>"www.abc.com/directory/test";
    [1]=>"www.abc.com/test";
    [2]=>"www.abc.com/directory/test";
    [3]=>"www.abc.com/test";
}

我只想要在/directory/这样的网址中包含某些内容的项目,并取消设置没有该项目的项目。

输出应该是:

Array
{
   [0]=>"www.abc.com/directory/test";                           
   [1]=>"www.abc.com/directory/test";
}

4 个答案:

答案 0 :(得分:1)

尝试使用array_filter这个:

$result = array_filter($data, function($el) {
    $parts = parse_url($el);
    return substr_count($parts['path'], '/') > 1;
});

如果path中有内容,则总是至少包含2个斜杠。

所以对于输入数据

$data = Array(
    "http://www.abc.com/directory/test",
    "www.abc.com/test",
    "www.abc.com/directory/test",
    "www.abc.com/test/123"
);

你的输出将是

Array
(
    [0] => http://www.abc.com/directory/test
    [2] => www.abc.com/directory/test
    [3] => www.abc.com/test/123
)

答案 1 :(得分:1)

没有闭包的例子。有时你只需先了解基础知识,然后再继续讨论这些问题。

$newArray = array();

foreach($array as $value) {
  if ( strpos( $value, '/directory/') ) {
     $newArray[] = $value;
  }
}

答案 2 :(得分:1)

有两种方法:

$urls = array(
    'www.abc.com/directory/test',
    'www.abc.com/test',
    'www.abc.com/foo/directory/test',
    'www.abc.com/foo/test',
);

$matches = array();

// if you want /directory/ to appear anywhere:
foreach ($urls as $url) {
    if (strpos($url, '/directory/')) {
        $matches[] = $url;
    }   
}

var_dump($matches);

$matches = array();

// if you want /directory/ to be the first path:
foreach ($urls as $url) {
    // make the strings valid URLs
    if (0 !== strpos($url, 'http://')) {
        $url = 'http://' . $url;
    }   

    $parts = parse_url($url);
    if (isset($parts['path']) && substr($parts['path'], 0, 11) === '/directory/') {
        $matches[] = $url;
    }   
}

var_dump($matches);

答案 3 :(得分:0)

 <?php
      $array = Array("www.abc.com/directory/test",
                "www.abc.com/test",
                "www.abc.com/directory/test",
                "www.abc.com/test",
              );

var_dump($array);

array_walk($array, function($val,$key) use(&$array){ 
     if (!strpos($val, 'directory')) { 
         unset($array[$key]);
     }
 });

var_dump($array);

php&gt; = 5.3.0