php - Split text on some, but not all spaces
I am working on a php project for cooking recipes and am stuck a bit of finding a decent way to split every ingredient from a text area box using PHP.
Here is an example of ingredient lines:
100 grams almonds (preferrably raw) or 1 egg
The text above should be split as follows:
100,
grams,
almonds (preferrably raw) && 1,
egg
Bear in mind, that some lines have just two words (spaces) but some would have more. I tried to split the words before the space into an array, however on lines with two words I am getting an error: Undefined offset...
Answer
Solution:
Match words starting composed of
[A-Za-z0-9_]
, then optionally continue matching for your specified occurrences. If you come to realise there are more trailing substrings to cover, just add to the non-capturing group. DemoOutput: