2014-10-31 45 views
1

這是迄今爲止我所編寫的代碼:如何從一個數組中刪除值?

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

+0

' 「無效」 或「nofollow的「 - 這個。你不能這樣做。 – naththedeveloper 2014-10-31 08:47:17

+0

你需要做的'如果(stristr($ unfinished_link, 「不活動」)|| stristr($ unfinished_link, 「nofollow的」)){...}' – naththedeveloper 2014-10-31 08:48:06

+0

我已刪除OR和剛剛離開的 「無效」 .. .still得到同樣的結果 – tommyg 2014-10-31 08:49:32

回答

1

如果你想找到裏面的一個字符串替換這,也許你indend使用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'); 
+0

@tommyg高興這有助於 – Ghost 2014-10-31 09:11:22

0

據我所知,你不能在方式組合參數,你試一下:

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

相反,你可以用

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

您迴應變量$ unfinished_link,它的不同之處在於$ link_body [$關鍵。 OK,該值是之前未設置$ link_body [$關鍵]相同,但它就像你正在做的:

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

當然,這個代碼將呼應的頭號因爲我有沒有設置一個變量和回聲等一個。 If的條件也不正確。

+0

確定@Serpes我也呼應了$ link_body [$關鍵]但我現在得到一個未定義的偏移誤差。 – tommyg 2014-10-31 08:56:39

+0

Obviusly。如果你沒有設置它,你不能迴應它。或者你回聲它在else語句或者您使用其他if語句如下:if(isset($ link_body [$關鍵])) – Serpes 2014-10-31 09:15:20

+0

Im相當慢,人。感謝您的幫助@Series – tommyg 2014-10-31 09:17:51

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]; 
} 
1

使用array_filter

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

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