Find substrings in string where substring encapsul

2019-02-28 03:23发布

问题:

I have a string in the format:

"The quick __grey__ fox jumps over the lazy __brown__ dog."

And I want to find and replace any words (or sometimes sentences) between the double underscores.

I am currently using preg_match_all in PHP:

$pattern = '/__(.*)__/';

This works fine... until it finds two sets of double underscores on the same line, such as in the above example, where it matches "__grey__" and "__brown__" as I want, but also "__grey__ fox jumps over the lazy brown__", which I do not want...

So my question is is there a way of matching only between the first and second instance, the third and fourth instance, etc?

I apologise if this has been asked before, but I'm really not sure how to phrase the question in a way concise enough to perform a useful search!

Thanks in advance.

回答1:

To find some substring between two closest identical delimiters, use lazy dot matching:

$pattern = '/__(.*?)__/';

See demo

To also match newlines, use /s modifier:

$pattern = '/__(.*?)__/s';