regex - PHP Regular expression match multiple keywords Where last keyword is optional -
i have following text , need find part of text after specific keyword
apple tasty fruit orange cool mango used make shakes banana healthy food here regular expression
/apple(.*)orange(.*)mango(.*)banana(.*)/is here output
array( 0 => array(0 => apple tasty fruit orange cool mango used make shakes banana healthy food) 1 => array(0 => tasty fruit) 2 => array(0 => cool) 3 => array(0 => used make shakes) 4 => array(0 => healthy food) ) it works fine if keywords in string apple, orange, mango, , banana. want regular expression still work if last keyword banana not provided.
apple tasty fruit orange cool mango used make shakes array( 0 => array(0 => apple tasty fruit orange cool mango used make shakes) 1 => array(0 => tasty fruit) 2 => array(0 => cool) 3 => array(0 => used make shakes) )
method 1
use ? quantifier let bandana "optional" along or specify end
apple(.*?)orange(.*?)mango(.*?)(?:banana(.*)|$) i've made lazy matching can work. because of this, need add new things:
(?: starts non-capture group banana(.*) selects "banana" , text after | or (if there no banana) $ matches end. ) demo
method 2
apple(.*?)orange(.*?)mango(.*?)(?:banana(.*))?$ makes "banana" optional this uses (?:)? make "banana" part optional. $ needed anchor know regex ends. can used make many parts optional without work:
apple(.*?)(?:orange(.*?))?mango(.*?)(?:banana(.*))?$ makes "banana , orange" optional demo
method 3
this require below exist:
apple(.*?)(?:orange(.*?)(?:mango(.*?)(?:banana(.*)|$)|$)|$)|$ demo
this bit hard explain checkout demo , mess 1 of words (apple, orange, banana, mango)
Comments
Post a Comment