从数组php中删除值

时间:2010-03-09 08:35:07

标签: php arrays

我有一个链接数组,我有另一个数组,其中包含我想要在列表中过滤的某些值 例如:

http://www.liquidshredder.co.uk/shop%3Fkw%3Dsurfboards%26fl%3D330343%26ci%3D3889610385%26network%3Ds
http://www.bournemouth-surfing.co.uk/index.php%3FcPath%3D32
http://www.stcstores.co.uk/wetsuit-range-sizing--pricing-info-1-w.asp
http://www.kingofwatersports.com/wetsuit-sale-c227.html
http://www.uk.best-price.com/search/landing/query/bodyboards/s/google/altk/Surf%2Band/koid/1944273223/
http://www.surfinghardware.co.uk/Results.cfm%3Fcategory%3D20%26kw%3Dbodyboards%26fl%3D11407%26ci%3D3326979552%26network%3Ds
http://www.teste.co.uk/adtrack/baod.html
http://www.teste.co.uk/bodyboards/
www.sandskater.co.uk/
www.sandskater.co.uk/bodyboards/+Bodyboards&sa=X&ei=GwSWS-KaGM24rAeF-vCKDA&ved=0CBMQHzAKOAo
http://www.extremesportstrader.co.uk/buy/water/bodyboarding/
www.extremesportstrader.co.uk/buy/water/bodyboarding/+Bodyboards&sa=X&ei=GwSWS-KaGM24rAeF-vCKDA&ved=0CBYQHzALOAo
www.circle-one.co.uk/+Bodyboards&sa=X&ei=GwSWS-KaGM24rAeF-vCKDA&ved=0CBkQHzAMOAo
http://www.teste.co.uk/bodyboards/p1
http://www.teste.co.uk/bodyboards/p2
http://www.amazon.co.uk/s/%3Fie%3DUTF8%26keywords%3Dbodyboards%26tag%3Dgooghydr-21%26index%3Daps%26hvadid%3D4764625891%26ref%3Dpd_sl_2lyzsfw1ar_e
http://www.teste.co.uk/bodyboards/p3
www.extremesportstrader.co.uk/buy/water/

我想删除“http://www.teste.co.uk”的所有实例?

我尝试了以下代码,但它不起作用:(

$remove=array("teste.co.uk","127.0.0.1","localhost","wikipedia.org","gmail.com","answers.yahoo.com");

foreach ($list[0] as $key=>$clean)
{
    if (in_array($clean,$remove)) 
    {               
        unset($list[0][$key]);
    }

    echo $clean;
    echo '<br>';   
}

4 个答案:

答案 0 :(得分:3)

根据Sjoerd的说法:

$url = parse_url($clean);
$host = $url['host'];

if (in_array($host,$remove)) 
{               
    unset($list[0][$key]);
}

使用parse_url()功能分析网址。

答案 1 :(得分:0)

in_array($ clean,$ remove)仅在字符串完全匹配时才有效。因此,如果$ remove包含“teste.co.uk”且$ clean包含“http://www.teste.co.uk/bodyboards/p3”,则返回false。

答案 2 :(得分:0)

如果数组$list[0]是您打印的列表,则问题是http://www.teste.co.uk/bodyboards/p1不在array("teste.co.uk","127.0...。只有确切的字符串"teste.co.uk"为。

因此你需要这样做:

$remove=array("teste.co.uk","127.0.0.1","localhost","wikipedia.org","gmail.com","answers.yahoo.com");

foreach ($list[0] as $key=>$url) {
    // We have to test for each badword individually
    foreach ($remove as $bad) {
        // Using this strpos trick, we can test if $bad is a substring of $url
        if (strpos($url, $bad) !== false) {
            unset($list[0][$key]);
            break;
        }
    }
}

答案 3 :(得分:0)

for($i=0; $i < count($array); $i++)
{
  //checks for full match
  if($array[$i] == $key)
  //use if(strpos($array[$i], $key) !== FALSE) to check for substrings.
  {
    array_splice($array, $i, 1)
    $i--;
  }
}