在字符串中查找子字符串封装在特定字符中的子字符串 [英] Find substrings in string where substring encapsulated in specific character
问题描述
我有一个格式如下的字符串:
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.
我目前在 PHP 中使用 preg_match_all:
I am currently using preg_match_all in PHP:
$pattern = '/__(.*)__/';
这很好用......直到它在同一行上找到两组双下划线,例如在上面的示例中,它根据我的需要匹配__grey__"和__brown__",但也__grey__ fox jumps over懒惰的棕色__",我不想要...
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!
提前致谢.
推荐答案
要在两个最接近的相同分隔符之间找到某个子字符串,请使用惰性点匹配:
To find some substring between two closest identical delimiters, use lazy dot matching:
$pattern = '/__(.*?)__/';
参见演示
要也匹配换行符,请使用 /s
修饰符:
To also match newlines, use /s
modifier:
$pattern = '/__(.*?)__/s';
这篇关于在字符串中查找子字符串封装在特定字符中的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!