phpregextext-extractionmention

Match string between two characters (@ and ,)


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];

Solution

  • 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:

    IDEONE demo:

    $re = "/(?<=@)[^,]+/"; 
    $str = "Hello @bob, my name is @jack,"; 
    preg_match_all($re, $str, $matches);
    print_r($matches);