如何过滤字符串以在符号后提取文本?

I have a function which can filter the text from a hashtag

function gethashtags($text)
        {
          //Match the hashtags
          preg_match_all('/(^|[^a-z0-9_])#([a-z0-9_]+)/i', $text, $matchedHashtags);
          $hashtag = '';
          // For each hashtag, strip all characters but alpha numeric
          if(!empty($matchedHashtags[0])) {
              foreach($matchedHashtags[0] as $match) {
                  $hashtag .= preg_replace("/[^a-z0-9]+/i", "", $match).',';
              }
          }
            //to remove last comma in a string
        return rtrim($hashtag, ',');
        }

So in my post file, the variable uses gethashtags() to extract the text but only if the string has a #. # being the trigger.

All I need is a similar function but uses @ as the trigger rather than a hash.

What function can achieve this result? I do not understand Regex's the slightest so I'm very sorry if this question comes across as vague as I've given my best effort to explain my problem.

Thanks in advanced!

I would simplify your function like this:

function gethashtags($text) {
   preg_match_all('/\B[@#]\K\w+/', $text, $matches);
   return implode(',', $matches[0]);
}
echo gethashtags("@Callum Hello! #hashtag @another #hashtag");

Explanation:

  • The (^|[^a-z0-9_]) part of your regex works like a non-word boundary \B.
  • Then we match either a @ or # character. \K throws away everything that it has matched up to that point.
  • Then we simply match word characters that follow either character and simply implode the results.

Output

Callum,hashtag,another,hashtag

I would suggest /([@#][^@^#]\S*)/g to fetch all @.. and #..

http://regex101.com/r/gD2oI8/2

With $sMatch{0} you can check for @ or # Or move the "(" behind the "[]" to skip it :-)