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


How can I filter a string to extract the text after a symbol?

我有一个函数可以从标签

中过滤文本
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, ',');
        }

所以在我的post文件中,变量使用gethashtags()来提取文本,但只有当字符串有一个#。#成为导火索。

我所需要的是一个类似的函数,但使用@作为触发器而不是散列。

什么函数可以达到这个结果?我不理解Regex的最轻微的,所以我很抱歉,如果这个问题遇到模糊,因为我已经尽我最大的努力来解释我的问题。

提前感谢!

我会这样简化你的函数:

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

:

  • 你的正则表达式的(^|[^a-z0-9_])部分就像一个非单词边界'B
  • 然后我们匹配@#字符。'K将所有匹配到该点的内容丢弃。
  • 然后我们简单地匹配任何一个字符后面的单词字符并简单地内爆结果。

Callum,hashtag,another,hashtag

我建议/([@#][^@^#]'S*)/g获取所有@..和# . .

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

使用$sMatch{0},您可以检查@或#或者将"("移到"[]"后面以跳过它:-)