I am trying to create a regex pattern to get the text that is between the following @
and ,
. For example the text is something like this:
Hello @bob, my name is @jack,
What I want to do is get the names bob
and jack
out of the string. Reading elsewhere I believe regex (PHP) is the best option. I have created my own pattern, but it does not work. The code I have is bellow. The comment variable contains the text.
$pat = '/\@\,/';
preg_match($pat, $comment, $matches);
echo $matches[1];
Your regex does not work because it only matches @,
sequence. You want something that is in-between.
You can use the following regex:
(?<=@)[^,]+
See regex demo
Regex explanation:
(?<=@)
- A look-behind that checks if there is a @
symbol before the text we are going to match with...[^,]+
- a negated character class that matches 1 or more characters other than a comma$re = "/(?<=@)[^,]+/";
$str = "Hello @bob, my name is @jack,";
preg_match_all($re, $str, $matches);
print_r($matches);