如何在 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

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

How to split a string by multiple delimiters in PHP?

phpregexstringsplit

提问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(中文?)“字符”的字符之间进行拆分

回答by alex

You can get the values into an array using Devin'sor Meder'smethod.

您可以使用DevinMeder 的方法将值放入数组中。

To get the output you want, you could probably do this

要获得您想要的输出,您可以这样做

echo implode("\n", $resultingArray);

Or use <br />if it's HTML you want.

或者,<br />如果它是您想要的 HTML,则使用。