使用preg_split从'你好,你好'到[你好,你好吗]

时间:2022-08-05 22:06:27

I want to split a string into two parts, the string is almost free text, for example:

我想将一个字符串分成两部分,字符串几乎是*文本,例如:

$string = 'hi how are you';

and i want the split to look like this:

我希望拆分看起来像这样:

array(
    [0] => hi
    [1] => how are you
)

I tried using this regex: /(\S*)\s*(\.*)/ but even when the array returned is the correct size, the values comes empty.

我尝试使用这个正则表达式:/(\S*)\s*(\.*)/但即使返回的数组是正确的大小,值也是空的。

What should be the pattern necessary to make this works?

使这个有效的模式应该是什么?

2 个解决方案

#1


What are the requirements? Your example seems pretty arbitrary. If all you want is to split on the first space and leave the rest of the string alone, this would do it, using explode:

有什么要求?你的例子似乎很随意。如果你想要的只是在第一个空格上分开并留下其余的字符串,那么就可以使用explode:

$pieces = explode(' ', 'hi how are you', 2);

Which basically says "split on spaces and limit the resulting array to 2 elements"

这基本上说“拆分空格并将结果数组限制为2个元素”

#2


You should not be escaping the "." in the last group. You're trying to match any character, not a literal period.

你不应该逃避“。”在最后一组。你试图匹配任何角色,而不是文字时期。

Corrected: /(\S*)\s*(.*)/

#1


What are the requirements? Your example seems pretty arbitrary. If all you want is to split on the first space and leave the rest of the string alone, this would do it, using explode:

有什么要求?你的例子似乎很随意。如果你想要的只是在第一个空格上分开并留下其余的字符串,那么就可以使用explode:

$pieces = explode(' ', 'hi how are you', 2);

Which basically says "split on spaces and limit the resulting array to 2 elements"

这基本上说“拆分空格并将结果数组限制为2个元素”

#2


You should not be escaping the "." in the last group. You're trying to match any character, not a literal period.

你不应该逃避“。”在最后一组。你试图匹配任何角色,而不是文字时期。

Corrected: /(\S*)\s*(.*)/