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
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.
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.
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.
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)
)
^(\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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With