1

I have some php code like this:

$input = "
__HELLO__
__HAPPY_BIRTHDAY__
__HELLO____HAPPY_BIRTHDAY__";

preg_match_all('/__(\w+)__/', $input, $matches);
print_r($matches[0]);

Currently the result of $matches[0] is this:

Array
(
    [0] => __HELLO__
    [1] => __HAPPY_BIRTHDAY__
    [2] => __HELLO____HAPPY_BIRTHDAY__
)

As you can see my regex is interpreting __HELLO____HAPPY_BIRTHDAY__ as one match, which I don't want.

I want the matches to return this:

Array
(
    [0] => __HELLO__
    [1] => __HAPPY_BIRTHDAY__
    [2] => __HELLO__
    [3] => __HAPPY_BIRTHDAY__
)

Where __HELLO____HAPPY_BIRTHDAY__ is split into __HELLO__ and __HAPPY_BIRTHDAY__. How can I do this?

(Each line will only ever have one underscore in between the outer underscores e.g. __HAPPY__BIRTHDAY__ is illegal)

Ethan
  • 4,295
  • 4
  • 25
  • 44
  • 1
    You are expected to try to **write the code yourself**. After [**doing more research**](https://meta.stackoverflow.com/q/261592/1011527) if you have a problem **post what you've tried** with a **clear explanation of what isn't working** and provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Jay Blanchard Jun 01 '17 at 17:19
  • Yes you're right @JayBlanchard I've written the php already but I thought it unnecessary to post. I'm updating my question right now. – Ethan Jun 01 '17 at 17:21
  • I've updated my question with the code now @JayBlanchard – Ethan Jun 01 '17 at 17:26
  • I would've just removed the PHP tag and left it as-is. @David – Daniel Jun 01 '17 at 17:29
  • True, I could've done that @Daniel Maybe then I wouldn't have got any downvotes :) Anyways I needed the code version. – Ethan Jun 01 '17 at 17:30

1 Answers1

2

You need to use the U modifier. This makes quantifiers "lazy".

$input = "
__HELLO__
__HAPPY_BIRTHDAY__
__HELLO____HAPPY_BIRTHDAY__";

preg_match_all('/__(\w+)__/U', $input, $matches);
print_r($matches[0]);

Output:

Array
(
    [0] => __HELLO__
    [1] => __HAPPY_BIRTHDAY__
    [2] => __HELLO__
    [3] => __HAPPY_BIRTHDAY__
)
Daniel
  • 1,229
  • 14
  • 24