1

I need to parse this string:

$str = "\n\n\nABC\n\nDEF\nGHI\n\n\nJKL" ;

into this array:

$arr = [
    "\n\n\n",
    "ABC\n",
    "\n",
    "DEF\n",
    "GHI\n",
    "\n\n",
    "JKL"
] ;

I tried many combinations, but no luck:

$arr = preg_match_all("/[^\n]+[\n]+/",$str,$out) ;

What Regex can handle that?

1
  • Why the three leading newlines are kept together but the three inner newlines come into separate strings in the posted example? What is the split rule? Commented Aug 12, 2017 at 9:59

1 Answer 1

3

This pattern does the job:

preg_match_all('~\n+|.+\n?~', $str, $matches);

demo

As an aside, preg_match_all returns the number of matches or false, the matches are stored in the third parameter.

Sign up to request clarification or add additional context in comments.

2 Comments

"/[^\n]+|[\n]+/" also works very well, thank you very much!
You are right, thats my hurriedness :), thank you again!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.