如何从数组中删除值?

时间:2014-10-31 08:43:44

标签: php arrays

这是我到目前为止编写的代码:

foreach ($link_body as $key => $unfinished_link)
{   
    #further Remove non ad links
    if (stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
    {   
        unset($link_body[$key]);
    }   

    echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
}

我没有收到任何错误消息,但我不断收到如下结果:

/cars/" />
/cars/">
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" rel="nofollow">(not what I wanted)
/cars/?layout=gallery" rel="nofollow">(not what I wanted)
/cars/2001-ford-escort-great-condition/1235588">(IS what I wanted)

我在哪里弄乱这些家伙? THX

5 个答案:

答案 0 :(得分:1)

如果你想在其中找到一个字符串,也许你可以改为使用stripos代替:

foreach ($link_body as $key => $unfinished_link) {
    // further Remove non ad links
    if(
        stripos($unfinished_link, 'inactive') !== false ||
        stripos($unfinished_link, 'nofollow') !== false
    ) {  
        unset($link_body[$key]);

    } else {
        echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
        // make sure your background is not white, or else your text will not be seen, at least on the white screen
    }
}

如果这是HTML标记,请考虑使用HTML解析器,尤其是DOMDocument,并搜索该属性:

$rel = $node->getAttribute('rel'); // or
$class = $node->getAttribute('class');

答案 1 :(得分:1)

你回应变量$ unfinished_link,它与$ link_body [$ key]不同。好的,在取消设置$ link_body [$ key]之前,这些值是相同的,但就像你在做的那样:

$a=1;
$b=1;
unset($a);
echo $b;

当然,这段代码将回应第一,因为我已取消设置变量并回显其他变量。 If的条件也是错误的。

答案 2 :(得分:1)

不要删除 foreach语句中的数组元素 记住要在foreach中删除的元素,在foreach后删除它们:

$elements_to_delete = {};
foreach ($link_body as $key => $unfinished_link)
{

    if(stristr($unfinished_link, "inactive" OR "nofollow") === TRUE) {   

        $elements_to_delete.push($key);
    }
}

// removing elements after foreach complete
foreach($key in $elements_to_delete){
    $link_body[$key];
}

答案 3 :(得分:1)

使用array_filter

function filterLink($link) {
 return  stripos($unfinished_link, 'inactive') === false &&
         stripos($unfinished_link, 'nofollow') === false
}

$unfinished_link = array_filter($unfinished_link, "filterLInk")

答案 4 :(得分:0)

据我所知,你不能以你在这里尝试的方式组合参数:

if(stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)

相反,您可以替换为

if(stristr($unfinished_link, "nofollow") === TRUE) || stristr($unfinished_link, "inactive") === TRUE)