简体   繁体   中英

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 !

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.

(\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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM