Divide the first space and the last space in the line and limit the output size to 3

Suppose I have a line:

ABC DEF SASF 123 (35) 

And my expected result is 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 that this RegEx will replace the contents in $str[0] and it will look like

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

How can I modify RegEx to output the expected result?

Online example: https://www.regex101.com/r/rK5lU1/2

+5
source share
2 answers

Just split the input line according to the expression below.

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

Just match the first word and drop it by adding \K next to \S+ . Then match the following one or more spaces. | OR juxtapose another space that came before the last word. \S+ matches one or more non-space characters.

Demo

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

Conclusion:

 Array ( [0] => ABC [1] => DEF SASF 123 [2] => (35) ) 
+4
source
 ^(\S+)\s+|\s+(?=\S+$) 

Try to share 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 a coincidence and capture of captures instead of separation.

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

Watch the demo

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

Source: https://habr.com/ru/post/1213295/


All Articles