使用逗号和连字符作为多个分隔符进行字符串分割

35

我想要用explode函数将一个字符串按以下方式拆分:

  1. 空格(\n \t 等)
  2. 逗号
  3. 短划线。例如 >> -

但是以下代码不起作用:

$keywords = explode("\n\t\r\a,-", "my string");

如何实现这个目标?
2个回答

68

Explode不能做到这一点。有一个很好的函数叫做preg_split可以实现这个功能。像这样做:

$keywords = preg_split("/[\s,-]+/", "This-sign, is why we can't have nice things");
var_dump($keywords);

这将输出:
  array
  0 => string 'This' (length=4)
  1 => string 'sign' (length=4)
  2 => string 'is' (length=2)
  3 => string 'why' (length=3)
  4 => string 'we' (length=2)
  5 => string 'can't' (length=5)
  6 => string 'have' (length=4)
  7 => string 'nice' (length=4)
  8 => string 'things' (length=6)

顺便提一下,不要使用split,它已经过时了。


13

如果您不喜欢正则表达式,但仍想分解内容,您可以在分解之前用一个字符替换多个字符:

$keywords = explode("-", str_replace(array("\n", "\t", "\r", "\a", ",", "-"), "-", 
  "my string\nIt contains text.\rAnd several\ntypes of new-lines.\tAnd tabs."));
var_dump($keywords);

这句话的意思是:这会导致以下结果:
array(6) {
  [0]=>
  string(9) "my string"
  [1]=>
  string(17) "It contains text."
  [2]=>
  string(11) "And several"
  [3]=>
  string(12) "types of new"
  [4]=>
  string(6) "lines."
  [5]=>
  string(9) "And tabs."
}

这种技术在连字符爆炸之前会对输入字符串进行6次遍历(完全遍历字符串x6)。我将使用shamittomar答案中的更简单的单函数调用,因为它只对输入字符串进行一次遍历。 - mickmackusa

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