在PHP中,我如何同时通过空格、逗号和换行符来分割一个字符串?

14

@GabrielSantos 很好的观点。欢迎 Michael! - nickhar
1个回答

23

既然您已经使用了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'] - Nick Strupat
根据操作系统的不同,添加回车符可能很有用,这样就像$split_strings = preg_split('/[\ \n\r,]+/', $your_string);(在\n后面添加了\r)。 - Unapedra
1
此外,为了避免在数组中返回“空字符串”,您应该在标志参数上使用PREG_SPLIT_NO_EMPTY,这样它就会像这样:preg_split('/[\ \n\r\,]+/', $your_string, -1, PREG_SPLIT_NO_EMPTY);,如此所述:http://php.net/manual/en/function.preg-split.php。 - Unapedra
为什么不使用 explode(' ', $my_string) - serraosays

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