2011-01-29 240 views
1
$data = "google,bing,searchengine,seo,search"; 

$exp = explode(",",$data); 

$filtr = array("google","bing"); 

$fdat = str_replace($filtr,"",$data); 

$clean = implode(",",$fdat); 

echo $clean; 

這給了放,,searchengine,seo,search如何擺脫空白?

如何才能擺脫前兩個空白的逗號?

回答

6

更好地得到您的分裂陣列$exp減去$filtr的區別:

$clean = implode(',', array_diff($exp, $filtr)); 

這也將避免你將只刪除一個字的子從bike,car,carpet刪除car時一樣的機會應導致bike,carpet和不在bike,pet

如果你想允許空格前後各單詞後,可以考慮使用trimpreg_split

$exp = preg_split('/\s*,\s*/', trim($data)); 

trim將刪除任何先前和結尾的空白,併爲preg_split該模式允許周圍逗號太多的空白。

+0

+1 ideone鏈接:http://ideone.com/c9J04 – 2011-01-29 15:56:00

+0

哇真是異想天開太短 – 2011-01-29 16:03:45

0

嘗試此代碼時出現錯誤。您可以使用以下方法來從一個逗號分隔的字符串中刪除谷歌&兵(即在陣列中):

$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
$diff = array_diff($exp, $filtr);
$clean = implode(",",$diff);
echo $clean;

0

你的代碼也可能是這樣的:

$data = "google,bing,searchengine,seo,search"; 

$exp = explode(",",$data); 

$filtr = array("google","bing"); 

foreach ($exp as $key => $item) { 
    if (in_array($key, $filtr)) unset($exp[$key]); 
} 

$clean = implode(",",$exp); 

echo $clean; 

其當$ data中的項目很少時很有用。對於大數組,它需要優化。

0

如果一個循環內檢查的價值,像這樣你會更好:

$data = "google,bing,searchengine,seo,search"; 
$exp = explode(",",$data); 
$filtr = array("google","bing"); 

foreach($exp as $k => $v) 
{ 
    if(in_array($v,$filtr)) 
    { 
     unset($ext[$k]); 
    } 
} 
$clean = implode(",",$ext); 
echo $clean;