如何用大字符串中的逗号删除字符串?

时间:2014-06-12 09:42:10

标签: php yii

我是PHP的新手,现在我已经解决了这个问题。我有一个这样的字符串:

$string = "qwe,asd,zxc,rty,fgh,vbn";

现在我想要用户点击" qwe"它将删除" qwe,"在$ string

Ex:$string = "asd,zxc,rty,fgh,vbn";

或删除" fhg,"

Ex:$string = "asd,zxc,rty,vbn";

我尝试使用str_replace,但它只是删除了字符串,并且在字符串之前仍然有逗号,如下所示:

$string = ",asd,zxc,rty,fgh,vbn";

任何人都可以提供帮助?感谢您的阅读

4 个答案:

答案 0 :(得分:1)

为了实现您的目标,阵列是您最好的朋友。

$string = "qwe,asd,zxc,rty,fgh,vbn";
$ExplodedString = explode( "," , $string ); //Explode them separated by comma

$itemToRemove = "asd";

foreach($ExplodedString as $key => $value){ //loop along the array
    if( $itemToRemove == $value ){ //check if item to be removed exists in the array
        unset($ExplodedString[$key]); //unset or remove is found
    }
}

$NewLook = array_values($ExplodedString); //Re-index the array key

print_r($NewLook); //print the array content

$NewLookCombined = implode( "," , $NewLook);

print_r($NewLookCombined); //print the array content after combined back

答案 1 :(得分:1)

这里的解决方案

$string = "qwe,asd,zxc,rty,fgh,vbn";
      $clickword = "vbn";          
      $exp = explode(",", $string);
      $imp =  implode(" ", $exp);

      if(stripos($imp, $clickword) !== false) {

       $var =  str_replace($clickword," ", $imp);

      }

      $str =  preg_replace('/\s\s+/',' ', $var);

      $newexp = explode(" ", trim($str));

      $newimp = implode(",", $newexp);
      echo $newimp;

答案 2 :(得分:1)

试试这个:

$break=explode(",",$string);
$new_array=array();
foreach($break as $newData)
{
 if($newData!='qwe')
 {
  $new_array[]=$newData;
 }
}
$newWord=implode(",",$new_array);

echo $newWord;

答案 3 :(得分:0)

如果您已设置模块,则可以尝试preg_replace http://uk3.php.net/manual/en/function.preg-replace.php。它允许您轻松地替换尾随或引导逗号:

preg_replace("/,*$providedString,*/i", '', "qwe,asd,zxc,rty,fgh,vbn");