【问题标题】:How do I extract words starting with a hash tag (#) from a string into an array如何将字符串中以井号 (#) 开头的单词提取到数组中
【发布时间】:2012-11-18 08:02:26
【问题描述】:

我有一个包含哈希标签的字符串,我正在尝试将标签拉出我认为我很接近但得到了一个具有相同结果的多维数组

  $string = "this is #a string with #some sweet #hash tags";

     preg_match_all('/(?!\b)(#\w+\b)/',$string,$matches);

     print_r($matches);

产生

 Array ( 
    [0] => Array ( 
        [0] => "#a" 
        [1] => "#some"
        [2] => "#hash" 
    ) 
    [1] => Array ( 
        [0] => "#a"
        [1] => "#some"
        [2] => "#hash"
    )
)

我只想要一个数组,每个单词都以哈希标记开头。

【问题讨论】:

    标签: php regex preg-match hashtag


    【解决方案1】:

    这可以通过/(?<!\w)#\w+/ regx 来完成

    【讨论】:

    • 如何以起始关键字提取所有世界?
    【解决方案2】:

    preg_match_all 就是这样做的。你总是得到一个多维数组。 [0] 是完全匹配,[1] 是第一个捕获组结果列表。

    只需访问$matches[1] 即可获得所需的字符串。 (带有所描述的无关 Array ( [0] => Array ( [0] 的转储是不正确的。您获得了一个子数组级别。)

    【讨论】:

      【解决方案3】:

      我认为这个功能会对你有所帮助:

      echo get_hashtags($string);
      
      function get_hashtags($string, $str = 1) {
          preg_match_all('/#(\w+)/',$string,$matches);
          $i = 0;
          if ($str) {
              foreach ($matches[1] as $match) {
                  $count = count($matches[1]);
                  $keywords .= "$match";
                  $i++;
                  if ($count > $i) $keywords .= ", ";
              }
          } else {
              foreach ($matches[1] as $match) {
                  $keyword[] = $match;
              }
              $keywords = $keyword;
          }
          return $keywords;
      }
      

      【讨论】:

        【解决方案4】:

        试试:

        $string = "this is #a string with #some sweet #hash tags";
        preg_match_all('/(?<!\w)#\S+/', $string, $matches);
        print_r($matches[0]);
        echo("<br><br>");
        
        // Output: Array ( [0] => #a [1] => #some [2] => #hash )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-13
          • 2020-03-15
          相关资源
          最近更新 更多