正则表达式也可以在两个文本边界和边界之间获取文本

时间:2012-12-17 07:30:57

标签: php regex

基于这个问题:Regular expression to extract text between square brackets

this is a [sample] string with [some] special words. [another one]

我需要在[sample]和[some]之间提取文本以及两个边界。换句话说,我想要将 [sample]字符串与[some]

匹配的正则表达式

1 个答案:

答案 0 :(得分:3)

试试这个:

/\[sample\].*?\[some\]/

您只需要转义方括号并在标记之间使用惰性匹配。

here on Regexr

如果文本可以在多行上,则需要使用s修饰符另外启用dotall模式:

/\[sample\].*?\[some\]/s

这使.也匹配换行符,默认情况下它没有。

here on Regexr