开发者

How do I get rid of Blank spaces?

开发者 https://www.devze.com 2023-02-07 04:41 出处:网络
$data = \"google,bing,searchengine,seo,search\"; $exp = explode(\",\",$data); $filtr = array(\"google\",\"bing\");
$data = "google,bing,searchengine,seo,search";

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

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

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

$clean = implod开发者_如何学JAVAe(",",$fdat);

echo $clean;

this gives out put ,,searchengine,seo,search

How can I get rid of first two blank commas?


Better get the difference of your splitted arrays $exp minus $filtr:

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

This will also avoid the chance that you will only remove a substring of another word like when removing car from bike,car,carpet should result in bike,carpet and not in bike,pet.

And if you want to allow whitespace before and after each word, consider using trim and preg_split:

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

trim will remove any preceding and trailing whitespace and the pattern for preg_split allows whitespace surrounding the comma too.


I'm getting an error when trying this code you did. You can use the following to remove google & bing (that are in an array) from a comma separated string:

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


Your piece of code could also look like this:

$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;

Its useful when there is few items in $data. For big arrays it would need optimizing.


You would be better if checking the value within a loop like so:

$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;
0

精彩评论

暂无评论...
验证码 换一张
取 消