如何在 PHP 中通过多个分隔符分割字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1452777/
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
How to split a string by multiple delimiters in PHP?
提问by omg
"something here ; and there, oh,that's all!"
"something here ; and there, oh,that's all!"
I want to split it by ;and ,
我想把它分成;和,
so after processing should get:
所以处理后应该得到:
something here
and there
oh
that's all!
回答by meder omuraliev
<?php
$pattern = '/[;,]/';
$string = "something here ; and there, oh,that's all!";
echo '<pre>', print_r( preg_split( $pattern, $string ), 1 ), '</pre>';
Updated answer to an updated question:
更新问题的更新答案:
<?php
$pattern = '/[\x{ff0c},]/u';
//$string = "something here ; and there, oh,that's all!";
$string = 'hei,nihao,a ';
echo '<pre>', print_r( preg_split( $pattern, $string ), 1 ), '</pre>';
回答by Devin Ceartas
$result_array = preg_split( "/[;,]/", $starting_string );
回答by pavium
The split() PHP function allows the delimiter to be a regular expression. Unfortunately it's deprecated and will be removed in PHP7!
split() PHP 函数允许分隔符为正则表达式。不幸的是,它已被弃用,并将在 PHP7 中删除!
The preg_split()function should be OK, and it returns an array:
在使preg_split()函数应该是行,并将其返回的数组:
$results = preg_split('/[;,]/', $string);
There are a few extra optional parameters which may be useful to you.
有一些额外的可选参数可能对您有用。
Is the first delimiter character in your edited example actually a 2 byte Unicode character?
您编辑的示例中的第一个分隔符实际上是一个 2 字节的 Unicode 字符吗?
Perhaps the preg_slit() function is treating the delimiter as three characters and splitting between the characters of the unicode (Chinese?) 'character'
也许 preg_slit() 函数将分隔符视为三个字符,并在 unicode(中文?)“字符”的字符之间进行拆分

