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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3679033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:40:51  来源:igfitidea点击:

Multiple explode characters with comma and - (hyphen)

phpstringsplitexplode

提问by WhatIsOpenID

I want to explodea string for all:

我想要explode一个字符串:

  1. whitespaces (\n \t etc)
  2. comma
  3. hyphen (small dash). Like this >> -
  1. 空格(\n \t 等)
  2. 逗号
  3. 连字符(小破折号)。像这样>> -

But this does not work:

但这不起作用:

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

How to do that?

怎么做?

回答by shamittomar

Explode can't do that. There is a nice function called preg_splitfor that. Do it like this:

爆炸不能这样做。有一个很好的函数调用 preg_split它。像这样做:

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

This outputs:

这输出:

  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)

BTW, do not use split, it is deprecated.

顺便说一句,不要使用split,它已被弃用。

回答by Florian Mertens

... or if you don't like regexes and you still want to explode stuff, you could replace multiple characters with just one character beforeyour explosion:

...或者如果你不喜欢正则表达式并且你仍然想要爆炸的东西,你可以爆炸之前用一个字符替换多个字符:

$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);

This blows into:

这吹成:

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