Search code examples
phpregexinstagram-api

How to get a string in regex and delete other after matching the string


my input is following

1 blah blah blah @username_. sblah sblah sblah

the output I need is following username_.

for now, I make this expression

^.*\@([a-zA-Z0-9\.\_]+)$

which working in following

1 blah blah blah @username_.

but if I use it for the full line it's not working

so its get the user and delete before the user but how I can make it delete the rest once it gets the user

Note I use regex101 for testing if you have a better tool please write it below.


Solution

  • Your pattern uses ^$ which means it needs a full match, your pattern is only partial.
    By adding a .* it becomes a full regex and it matches as expected.

    "/^.*\@([a-zA-Z0-9\.\_]+).*$/"
    

    https://3v4l.org/i4pVd

    Another way to do it is to use a partial regex like this.
    It skips anything up to the @ and then captures all to a dot

    $str = "1 blah blah blah @username_. sblah sblah sblah";
    preg_match("/.*?\@(.*?\.)/", $str, $match);
    
    var_dump($match);
    

    https://3v4l.org/mvBYI