PHP正则表达式匹配多个关键字最后一个关键字是可选的

时间:2015-06-13 22:45:19

标签: php regex

我有以下文字,我需要在特定关键字

后找到部分文字
Apple is tasty fruit
    orange is cool
mango is used to make shakes
        banana is a healthy food

这是我的正则表达式

/apple(.*)orange(.*)mango(.*)banana(.*)/is

这是输出

array(
    0   =>  array(0 => Apple is tasty fruit orange is cool mango is used to make shakes banana is a healthy food)
    1   =>  array(0 => is tasty fruit)
    2   =>  array(0 => is cool)
    3   =>  array(0 => is used to make shakes)
    4   =>  array(0 => is a healthy food)
)

如果所有关键字都在字符串中,那么它的效果非常好 苹果,橘子,芒果和香蕉。但是,如果没有提供最后一个关键字banana,我想要一个仍然有效的正则表达式。

Apple is tasty fruit
    orange is cool
mango is used to make shakes

array(
        0   =>  array(0 => Apple is tasty fruit orange is cool mango is used to make shakes)
        1   =>  array(0 => is tasty fruit)
        2   =>  array(0 => is cool)
        3   =>  array(0 => is used to make shakes)
    )

1 个答案:

答案 0 :(得分:1)

方法1

使用?量词让bandana成为“可选”以及OR以指定结尾

apple(.*?)orange(.*?)mango(.*?)(?:banana(.*)|$)

我已经使用延迟匹配制作了所有内容,因此它可以正常工作。因此,我们需要添加一些新东西:

(?:            Starts non-capture group
   banana(.*)  Selects "banana" and the text after it
|              OR (if there is no banana)
   $           matches end.
)

Demo

方法2

apple(.*?)orange(.*?)mango(.*?)(?:banana(.*))?$
Makes "banana" optional

这使用(?:)?使“香蕉”部分可选。需要$作为锚来知道正则表达式的结束位置。这可以用来使许多部件可选而无需太多工作:

apple(.*?)(?:orange(.*?))?mango(.*?)(?:banana(.*))?$ 
Makes "banana and orange" optional

Demo

方法3

这将要求它下面的所有内容都存在:

apple(.*?)(?:orange(.*?)(?:mango(.*?)(?:banana(.*)|$)|$)|$)|$

Demo

这有点难以解释所以只需检查演示并弄乱其中一个词(苹果,橙子,香蕉,芒果)