在PHP中通过多个分隔符拆分字符串

6

字符串能否根据多个分隔符解析成数组?如下代码所示:

$str ="a,b c,d;e f";
//What i want is to convert this string into array
//using the delimiters space, comma, semicolon
2个回答

18

PHP

$str = "a,b c,d;e f";

$pieces = preg_split('/[, ;]/', $str);

var_dump($pieces);

CodePad

输出

array(6) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
}

你知道吗,在我使用 PHP 的所有时间里,我从未使用过那个函数——但知道它的存在很不错。非常酷。 - KyleFarris
3
当我需要将用户输入的内容按逗号进行分割时,我通常使用preg_split('/,\s*/', $csv),而不是使用explode()array_map()trim() - alex
那正是我正在寻找的完美答案。非常感谢。 - Rolen Koh

-1

2
你需要多次调用strtok来构建数组,strtok本身并不构建数组,只是逐个返回字符串部分。 - Ben

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接