如果项目中包含前缀,则从数组中删除项目

时间:2016-06-30 17:46:12

标签: php

我正在尝试删除数组$links中所有不以$mustcontain中的前缀开头的网址。

编辑:由于某种原因,stackoverflow不允许http://www。所以我用url替换它

代码:

// 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] );
        }
    }
}

示例:基于$mustcontain = 'url/sub/dir/';的上述标准,我保留的标记应保留。:

$links = array (
  0 => 'url/sub/dir/1234', // keep
  1 => 'url/sub/dir/', // keep
  2 => 'url/13214124',
  3 => 'url/sub/123123123123',
);

1 个答案:

答案 0 :(得分:3)

我就是这样做的:

// 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]);
    }
}

我们正在使用!==进行严格检查,因为0(这是我们想要的)和false(我们不想要的)会评估为否则false