$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
如何摆脱前两个空白逗号?
答案 0 :(得分:6)
最好区分分割的数组$exp
减去$filtr
:
$clean = implode(',', array_diff($exp, $filtr));
这也可以避免您只删除其他字词的子字符串,例如从car
中移除bike,car,carpet
而导致bike,carpet
而不是bike,pet
。
如果您想在每个字词之前和之后允许空格,请考虑使用trim
和preg_split
:
$exp = preg_split('/\s*,\s*/', trim($data));
trim
将删除任何前置和尾随空格,preg_split
的模式也允许逗号周围的空格。
答案 1 :(得分:0)
我在尝试使用此代码时遇到错误。您可以使用以下内容删除google& bing(在数组中)来自逗号分隔的字符串:
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
$diff = array_diff($exp, $filtr);
$clean = implode(",",$diff);
echo $clean;
答案 2 :(得分: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中的项目很少时,它很有用。对于大型阵列,需要进行优化。
答案 3 :(得分: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;