michelleisconfused michelleisconfused - 5 months ago 11
PHP Question

remove items from array if prefix isnt contained in the item

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',
);

Answer

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.