php - Split text on some, but not all spaces

220

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...

251

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. Demo

$string = '100 grams almonds (preferrably raw) && 1 egg';

var_export(
    preg_match_all(
        '/\w+(?: && \d+| \([^)]+\))*/',
        $string,
        $m
    )
    ? $m[0]
    : []
);

Output:

array (
  0 => '100',
  1 => 'grams',
  2 => 'almonds (preferrably raw) && 1',
  3 => 'egg',
)

People are also looking for solutions to the problem: PHP download gives me empty pdf

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.