Reputation: 980
I'm trying to pick out the word/phrase (wrapped in hashtags) after a certain string. For instance:
This is an example paragraph and I am trying to get the word/phrase after the artist name which is in hash tags, such as @calvinharris #feel so close#.
Now, I have been able to successfully grab all @words from the string using:
preg_match_all('!@(.+)(?:\s|$)!U', $string, $matches)
But is there a way I can easily grab the hashtag enclosed phrases (if they're there) after an @name?
Upvotes: 1
Views: 158
Reputation: 6388
This should do the trick.
preg_match_all('/@(\w+)\s?(?:#([^#]+)#)?/', $string, $matches);
$matches[1]
will contain the "artist name"
$matches[2]
will contain the optional phrase
Upvotes: 1
Reputation: 3381
Try the following regexp:
^@(.+)#(.+)#$
And if you want to remove spaces
^@(.+)\S*#(.+)\S*#$
And if you want to trim a lot
^@\S*(.+)\S*#\S*(.+)\S*#$
And you are not sure there is hashtag (or wathever it is called)
^@\S*(.+)\S*(#\S*(.+)\S*#)?$
Upvotes: 2
Reputation: 737
You can easily make this by using groups and preg_match.
$name = "calvinharris";
preg_match('/@'.$name.' #([\w\s]+)#/', "This is an example paragraph and I am trying to get the word/phrase after the artist name which is in hash tags, such as @calvinharris #feel so close#. ", $match);
echo '$match = ' . $match[1]; //feel so close
The idea is to use grouping (the things between brackets) and get this group.
Upvotes: 1
Reputation: 2134
This seems to do the trick (no / / delimiters included):
@(\S+)\s+#(.+?)#
"1 or more non-whitespace, followed by 1 or more whitespace, followed by some characters enclosed by #"
Note the use of the non-greedy operator (?) for the text inside the hash.
EDIT:
after preg_match_all
, $match[1] will correspond to the artist name, $match[2] to the text in hash tags
Upvotes: 1
Reputation: 1024
Remember to make your character sets as specific as possible:
preg_match_all('!@([^\s]+) #([^#]+)#!U', $string, $matches)
[^\s]+
will match up to the first white space, [^#]+
will match up to the closing hash tag.
Upvotes: 1