Vitaliy Isikov
Vitaliy Isikov

Reputation: 3654

PHP regex get only first value in between two strings

I have a string that looks like this

aa bcdef123efg hh aa lklmasd456 hh (whitespace and bolding is used for illustration)

If I have 456, I want to find where 456 is and grab everything in between aa and hh.

This is the regex that I was able to come up with so far (?=aa)(.*)456(.*)(?=hh)

However, that doesn't stop at the first occurance of aa it encounters (backwards from the 456 match)

What would be the proper syntax for what I'm trying to achieve.

Upvotes: 1

Views: 79

Answers (1)

anubhava
anubhava

Reputation: 784998

You can use this lookaround based regex:

aa((?:(?!hh).)*?456(?:(?!hh).)*?)hh

RegEx Demo

Upvotes: 1

Related Questions