-1

I'm trying to remove all URLs in my array $links which don't start with the prefix in $mustcontain.

Edit: For some reason stackoverflow doesn't permit http://www. so I substituted it with url

Code:

// url prefix each link must start with
$mustcontain = 'url/sub/dir/';

//  Check each link
foreach ( $links as $key => $text )  
{
//  Search $links to make sure it starts with $mustcontain
foreach ( $mustcontain as $goodlink )
{
    if ( stristr( $text, $goodlink ) )
    {
        //  Remove links which dont start with the prefix
            unset( $links[$key] );
        }
    }
}

Example: Based on the criteria above of $mustcontain = 'url/sub/dir/'; The ones I marked should be kept.:

$links = array (
  0 => 'url/sub/dir/1234', // keep
  1 => 'url/sub/dir/', // keep
  2 => 'url/13214124',
  3 => 'url/sub/123123123123',
);
FirstOne
  • 6,033
  • 7
  • 26
  • 45

1 Answers1

3

This is how I would do it:

// url prefix each link must start with
$mustcontain = 'url/sub/dir/';

//  Check each link
foreach ( $links as $key => $text )  
{
    if (strpos($text, $mustcontain) !== 0) {
        // $mustcontain wasn't found in the beginning of $text
        // so unset that element from the array.
        unset($links[$key]);
    }
}

We're using !== for strict checking, since 0 (which is what we want) and false (which we don't want) would evaluate as false otherwise.

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40