PHP替换字符串或数组

时间:2016-12-17 21:44:37

标签: php

您好我有这个变量

$str="101,102,103,104,105,@,106@107"
//or array
$str_arr = array(  0 => '101',  1 => '102',  2 => '103',  3 => '104',
                   4 => '105',  8 => '@' ,  9 => '106@ 107');

我想在逗号

之间删除符号@

符号可能是/,\, - ,|不是逗号 数字之间的符号是正确的,因此它仍然是(键9)

我不知道,如果我有这些案件,但我会研究它

$str="101,102,103,104,105@, 106" // One of the symbols  in the end of number
$str="101,102,103,104,105,@106" // One of the symbols in the  the beginning of number

这是不同的可能性

$str="101,102,103,/,104|,@105,106@107" //replace all symbol in the beginning and the end of number not betwwen number

这是结果

$str="101,102,103,104,105,106@107";

由于

1 个答案:

答案 0 :(得分:0)

使用,爆炸将字符串转换为数组。使用foreach循环解析数组。 trim() @或每个字符串开头和结尾的任意字符集@-|\/,然后检查空值并将非空值推送到$arr数组。然后,您可以使用implode将数组加入到字符串中。你可以这样做:

 $arr = array();
 $str="101,102,103,104,105,@,106@107";
 $str = explode(',', $str);
 foreach($str as $s){
     $s = trim($s, "@-|\/");
     if(!empty($s)){
        $arr[] = $s;
     }
 }
$final_str = implode(',', $arr);        
var_dump($final_str);