【问题标题】:In PHP, how can I split a string by whitespace, commas, and newlines at the same time [duplicate]在PHP中,如何同时用空格、逗号和换行符分割字符串[重复]
【发布时间】:2023-04-04 07:25:01
【问题描述】:

可能重复:
How to split a string by multiple delimiters in PHP?

同时用三个分隔符(特别是单个空格、换行符和逗号)分割字符串的最有效方法是什么?

【问题讨论】:

  • @GabrielSantos 好点。欢迎迈克尔!

标签: php arrays split explode delimiter


【解决方案1】:

既然你已经用php 标记了你的问题,我会坚持下去。请参阅preg_split

$split_strings = preg_split('/[\ \n\,]+/', $your_string);

这也将保持数组干净,如果您的字符串类似于some, ,,string,它仍然会导致['some', 'string'] 而不是['some', '', '', '', 'string']

【讨论】:

  • 加入转义字符怎么样? hey 'this is' some text 产生 ['hey', 'this is', 'some', 'text']?
  • 根据操作系统,添加返回字符可能很有用,所以它就像 $split_strings = preg_split('/[\ \n\r\,]+/', $your_string ); (在 \n 之后添加 \r)
  • 另外,为了避免在数组上返回“空字符串”,你应该在 flags 参数上使用PREG_SPLIT_NO_EMPTY,所以它就像preg_split('/[\ \n\r\,]+/', $your_string, -1, PREG_SPLIT_NO_EMPTY);,如:php.net/manual/en/function.preg-split.php
  • 为什么要注意explode(' ', $my_string)
猜你喜欢
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 2018-03-22
相关资源
最近更新 更多