user1404617
user1404617

Reputation: 605

How to make the second group in a regex match before the first

I have the following regex in php.

The first group or parenthesized sub pattern is to select an optional date from the beginning of the string.

The last group is supposed to get another optional date from the end of the string. And the (.+) in the middle is supposed to get whatever is left in the string. The middle part does not work unless there is a date at the start or end of the string.

How can I make it work even if there is no date at the start or end of the string? The third group needs to match first and let the second match whatever is left. Thanks.

Here is what i have so far, preg_match("/(^\d{1,2}[\/.]\d{1,2}[\/.]\d{1,4}\b)?(.+)(\b\d{1,2}[\/.]\d{1,2}[\/.]\d{1,4}$)/", $string, $match);

For example, I would like (.+) to get My text here 55 out of 1/5/18 My text here 55 5.6.2016 and 1/5/18 My text here 55 and My text here 55.

Upvotes: 0

Views: 789

Answers (1)

mleko
mleko

Reputation: 12243

If I understand correctly

^(\d{1,2}[\/.]\d{1,2}[\/.]\d{1,4}\b)?(.+?)(\b\d{1,2}[\/.]\d{1,2}[\/.]\d{1,4})?$

should work for you.

Matches any text that can be surrounded dates

11/11/11 text 12/12/12

11/11/11 text

text 12/12/12

https://regex101.com/r/frkGiH/1/tests

Upvotes: 1

Related Questions