拆分字符串中的第一个空格和最后一个空格,并将输出的大小限制为3

时间:2022-08-22 13:16:44

Suppose I have a string:

假设我有一个字符串:

ABC DEF SASF  123 (35)

And my expected output like:

我的预期输出如下:

Array (
     [0] => ABC
     [1] => DEF SASF  123
     [2] => (35)
)

I am trying to do this with $str = preg_split("/(^\S+\s+)|\s+(?=\S+$)/",$str, 3); But the current problem is this RegEx will replace the content in $str[0] and it would be like

我试图用$ str = preg_split(“/(^ \ S + \ s +)| \ s +(?= \ S + $)/”,$ str,3)来做这个;但目前的问题是这个RegEx将取代$ str [0]中的内容,它就像是

Array (
     [0] => 
     [1] => DEF SASF  123
     [2] => (35)
)

How can I modify the RegEx to output my expected result ?

如何修改RegEx以输出我的预期结果?

The online example: https://www.regex101.com/r/rK5lU1/2

在线示例:https://www.regex101.com/r/rK5lU1/2

2 个解决方案

#1


4  

Just split your input string according to the below regex.

只需根据以下正则表达式拆分输入字符串。

^\S+\K\s+|\s+(?=\S+$)

Just match the first word and then discard it by adding \K next to \S+. Then match the following one or more spaces. | OR match one more spaces which was just before to the last word. \S+ matches one or more non-space characters.

只需匹配第一个单词,然后通过在\ S +旁边添加\ K来丢弃它。然后匹配以下一个或多个空格。 |或者匹配前一个单词的前一个空格。 \ S +匹配一个或多个非空格字符。

DEMO

$str = "ABC DEF SASF  123 (35)";
$match = preg_split('~^\S+\K\s+|\s+(?=\S+$)~', $str);
print_r($match);

Output:

Array
(
    [0] => ABC
    [1] => DEF SASF  123
    [2] => (35)
)

#2


2  

^(\S+)\s+|\s+(?=\S+$)

Try splitting by this. Sample code.

尝试分裂。示例代码。

preg_split('/^(\S+)\s+|\s+(?=\S+$)/', 'ABC DEF SASF  123 (35)', -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)

Or just match and grab the captures instead of split.

或者只是匹配并抓住捕获而不是拆分。

^(\S+)\s+(.*?)\s+(\S+)$

See demo

$re = "/^(\\S+)\\s+(.*?)\\s+(\\S+)$/";
$str = "ABC DEF SASF 123 (35)";

preg_match_all($re, $str, $matches);

#1


4  

Just split your input string according to the below regex.

只需根据以下正则表达式拆分输入字符串。

^\S+\K\s+|\s+(?=\S+$)

Just match the first word and then discard it by adding \K next to \S+. Then match the following one or more spaces. | OR match one more spaces which was just before to the last word. \S+ matches one or more non-space characters.

只需匹配第一个单词,然后通过在\ S +旁边添加\ K来丢弃它。然后匹配以下一个或多个空格。 |或者匹配前一个单词的前一个空格。 \ S +匹配一个或多个非空格字符。

DEMO

$str = "ABC DEF SASF  123 (35)";
$match = preg_split('~^\S+\K\s+|\s+(?=\S+$)~', $str);
print_r($match);

Output:

Array
(
    [0] => ABC
    [1] => DEF SASF  123
    [2] => (35)
)

#2


2  

^(\S+)\s+|\s+(?=\S+$)

Try splitting by this. Sample code.

尝试分裂。示例代码。

preg_split('/^(\S+)\s+|\s+(?=\S+$)/', 'ABC DEF SASF  123 (35)', -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)

Or just match and grab the captures instead of split.

或者只是匹配并抓住捕获而不是拆分。

^(\S+)\s+(.*?)\s+(\S+)$

See demo

$re = "/^(\\S+)\\s+(.*?)\\s+(\\S+)$/";
$str = "ABC DEF SASF 123 (35)";

preg_match_all($re, $str, $matches);