2

I have the following Array :

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

I only want the items that have something in middle in URL like /directory/ and unset the items that do not have that.

Output should be like:

Array
{
   [0]=>"www.abc.com/directory/test";                           
   [1]=>"www.abc.com/directory/test";
}
hakre
  • 193,403
  • 52
  • 435
  • 836
sohel14_cse_ju
  • 2,481
  • 9
  • 34
  • 55
  • What have you tried so far and into which problem did you run with it? Is there something special about the strings? They don't look like valid URLs. – hakre Feb 25 '12 at 14:04

4 Answers4

1

Try using array_filter this:

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

If you have something inside path will allways contain at least 2 slashes.

So for input data

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

you output will be

Array
(
    [0] => http://www.abc.com/directory/test
    [2] => www.abc.com/directory/test
    [3] => www.abc.com/test/123
)
dfsq
  • 191,768
  • 25
  • 236
  • 258
1

An example without closures. Sometimes you just need to understand the basics first, before you can move on to the neater stuff.

$newArray = array();

foreach($array as $value) {
  if ( strpos( $value, '/directory/') ) {
     $newArray[] = $value;
  }
}
Evert
  • 93,428
  • 18
  • 118
  • 189
1

A couple of approaches:

$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);
cmbuckley
  • 40,217
  • 9
  • 77
  • 91
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 >= 5.3.0

Vitalii Lebediev
  • 632
  • 2
  • 10
  • 19