regular expression to detect mentions but not detecting emails

php, regex

Solution

before the @ sign there should be a space

You can use lookbehind (edited based on OP's comment below):

preg_match('/(?<= |^)@[^@ ]+/', $image->caption->text, $matches);

Working Demo

Problem

I have the following code: ``` preg_match('/@([^@ ]+)/', $image->caption->text, $matches) ``` and I wanted to basically detect mentions in a string. However the issue now is that it is confused with email address such that it detects email as a mention, so for example if I have `aksdjasd@yahoo.com` then this counts as a match. I guess what I want to say here is that before the @ sign there should be a space. But how do I put that in to this regex? EDIT: I also wanted to detect @mentions at the beginning of the string as well

Original source