$num=“1,2,3,4,5,6,7,8,86,9”;
1,如果格式是这样子就用,PHP的preg_replace ,采用正则运算,去掉所有重复的","。
preg_replace(’#,{2,}#’,’,’,$num);
$num=",1,23,4,5,6,7,8";
2,如果字符串前面的逗号应该用Itrim来去除","。
ltrim($num, “,”);
$num=“1,2,3,4,5,”;
2,如果字符串后面的逗号应该用rtrim来去除","。
rtrim($num, “,”);
另:
关于php7+版本中 preg_replace /e修饰符已经弃用,可以preg_replace_callback的回调函数/e修饰符
//第一种, 常用, 适合单一任务
$template = preg_replace_callback( //处理eval
"/[\n\r\t]*\{eval\s+(.+?)\}[\n\r\t]*/is",
function ($matches) { return str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", " $matches[1] ?>")); },
$template
);
//第二种, 当你需要同一正则处理多个任务时 [推荐]
function stripvtags($expr) {
$expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));
return $expr;
}
$template = preg_replace_callback( //处理eval
"/[\n\r\t]*\{eval\s+(.+?)\}[\n\r\t]*/is",
function ($matches) { return stripvtags(" $matches[1] ?>"); },
$template
);
$template = preg_replace_callback( //处理echo
"/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/is",
function ($matches) { return stripvtags(" echo $matches[1] ?>"); },
$template
);
//第三种 跟第一种差不多, 只不过是分开写
class Template {
public function test() {
$template = preg_replace_callback( //处理eval
"/[\n\r\t]*\{eval\s+(.+?)\}[\n\r\t]*/is",
array($this, 'stripvtagsEval'),
$template
);
}
protected function stripvtagsEval($matches) {
return str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", " $matches[1] ?>"));
}
}