patriciopa
patriciopa

Reputation: 13

How to get an unknown word before a known one with Regex in PHP

I have this text:

andres wins Pot (9.50) with a Full House

and i want to get the word "andres". This is a player name (variable), that is always shown before the word "wins".

I need to use preg_match_all function, and i am trying with:

%(?:\S+\s)?\S*wins%

But it returns me:

andres wins

I need only, andres.

Thank you !

Upvotes: 1

Views: 671

Answers (2)

vks
vks

Reputation: 67968

(\w+)(?=\s*wins)

You can also use this.Grab the match[1].This will not capture anything else.See demo.

http://regex101.com/r/xO7bK2/1

Upvotes: 0

hwnd
hwnd

Reputation: 70732

Use a capturing group instead of a non-capturing group. This should be enough to match the preceding word.

(\w+)\s*wins

You need to reference $matches[1] to return your match result.

Upvotes: 2

Related Questions