Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name from hashtag using regex

Tags:

regex

php

hashtag

I have this string/content:

@Salome, @Jessi H and @O'Ren were playing at the @Lean's yard with "@Ziggy" the mouse.

Well, I am trying to get all names focuses above. I have used @ symbol to create like a hash to be used in my web. If you note, there are names with spaces between like @Jessi H and characters before and after like @Ziggy. So, I don't my if you suggest me another way to manage the hash in another way to get it works correctly. I was thinking that for user that have white spaces, could write the hash with quotes like @"Jessi H". What do you think? Other examples:

@Lean's => @"Lean"'s  
@Jessi H => @"Jessi H"  
"@Jessi H" => (sorry, I don't know how to parse it)  
@O'Ren => @"O'Ren" 

What I have do? I'm starting using regex in php, but some SO questions have been usefull for me to get started, so, these are my tries using preg_match_all function firstly:

Result of /@(.*?)[,\" ]/:

Array ( [0] => Salome [1] => Jessi [2] => Charlie [3] => Lean's [4] => Ziggy" ) )

Result of /@"(.*?)"/ for names like @"name":

Empty array

Guys, I don't expect that you do it all for me. I think that a pseudo-code or something like this will be helpful to guide me to the right direction.

like image 680
manix Avatar asked Mar 13 '26 21:03

manix


1 Answers

Try the following regex: '/@(?:"([^"]+)|([^\b]+?))\b/'

This will return two match groups, the first containing any quoted names (eg @"Jessi H" and @"O'Ren"), and the second containing any unquoted names (eg @Salome, @Leon)

$matches = array();
preg_match_all('/@(?:"([^"]+)|([^\b]+?))\b/', '@Salome, @"Jessi H" and @"O\'Ren" were playing at the @Lean\'s yard with "@Ziggy" the mouse.', $matches);
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => @Salome
            [1] => @"Jessi H
            [2] => @"O'Ren
            [3] => @Lean
            [4] => @Ziggy
        )

    [1] => Array
        (
            [0] => 
            [1] => Jessi H
            [2] => O'Ren
            [3] => 
            [4] => 
        )

    [2] => Array
        (
            [0] => Salome
            [1] => 
            [2] => 
            [3] => Lean
            [4] => Ziggy
        )

)
like image 94
Kelvin Avatar answered Mar 15 '26 11:03

Kelvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!