Find substrings in string where substring encapsulated in specific character

六眼飞鱼酱① 提交于 2019-12-20 04:31:56

问题


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';


来源:https://stackoverflow.com/questions/32742026/find-substrings-in-string-where-substring-encapsulated-in-specific-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!