user3362083
user3362083

Reputation: 11

match regex php between two string with string in middle

I would like to get a string made of one word with a delimiter word before and after it

i tried but doen t work

$stringData2 = file_get_contents('testtext3.txt');
$regular2=('/(?<=first del)*MAIN WORD(?=last del)*\s');      

preg_match_all($regular2,                          
$stringData2,
$out, PREG_PATTERN_ORDER);

thank you very much for any help

Upvotes: 0

Views: 647

Answers (3)

Philip Bennison
Philip Bennison

Reputation: 527

If you want the delimiter string included in the match, then you should not be using lookahead or look or look behind. It should be something rather basic, like this.

/\s?first del MAIN WORD last del\s?/

If you do want to return JUST the MAIN WORD part of the match, then this will work.

/(?<=\s?first del)MAIN WORD(?=last del\s?)/

Put a 'i' at the very end of that to make it case insensitive, if you want. I only mention this, because in the example you gave me above has different case between the example text and the desired response.

Upvotes: 0

deanosaur
deanosaur

Reputation: 611

This regex

(?<=xx)[^\s]*(?=yy)

matches hello in:

xxhelloyy

but fails to match in:

xxhello worldyy

This is probably what you're looking for.

Upvotes: 0

user557597
user557597

Reputation:

No quantifier needed, add delimeter at end, put \s inside lookahead.

'/(?<=first del)MAIN WORD(?=last del\s)/'

Upvotes: 2

Related Questions