$re = '/^[^\S\n]*(\w+(?: +\w+)*?)(?=:| joined the lobby$)/m';
$str = 'Hey Guys,
I want to filter the usernames out of the following string from a game lobby:
Username123 joined the lobby
User name 123 joined the lobby
Otheruser 12 joined the lobby
Username123: Hello Guys!
o t h e ruser23 joined the lobby
Player1 3 joined the lobby
As you can see, the username can consist of characters, numbers and spaces. Before every Username a new line starts and the "joined the lobby" part is fixed. However between 2 users joining an already joined user can write a textmessage to the whole lobby.
How can I extract the 5 unique usernames?
I joined the lobby
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php