Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split the first space and the last space in a string and limit the size of output in 3

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

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

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

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

like image 800
user3571945 Avatar asked Feb 13 '15 04:02

user3571945


People also ask

How do you split the first space in a string?

Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.

How do you split a string with spaces?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

How do you split a string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

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.

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)
)
like image 100
Avinash Raj Avatar answered Oct 05 '22 18:10

Avinash Raj


^(\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);
like image 38
vks Avatar answered Oct 05 '22 16:10

vks