多个带逗号和 - (连字符)的分解字符

2022-08-30 13:21:20

我想为所有人提供一个字符串:explode

  1. 空格(\n \t 等)
  2. 逗点
  3. 连字符(小破折号)。像这样>>——

但这不起作用:

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

如何做到这一点?


答案 1

爆炸不能做到这一点。有一个很好的函数叫做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


答案 2

...或者,如果您不喜欢正则表达式,并且仍然想爆炸内容,则可以在爆炸仅用一个字符替换多个字符:

$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."
}

推荐