【问题标题】:How to capture substrings that start with a hashtag?如何捕获以主题标签开头的子字符串?
【发布时间】:2017-12-04 09:36:16
【问题描述】:

我正在寻找使用正则表达式、preg_match()preg_split() 或任何其他方式从文本中拆分单词的 php 代码。

$textstring="one #two three #four #five";

我需要将#two#four#five 保存为数组元素。

【问题讨论】:

  • 纯代码编写请求在 Stack Overflow 上是题外话——我们希望这里的问题与特定编程问题有关——但我们很乐意帮助您自己编写!告诉我们what you've tried,以及您遇到的问题。这也将有助于我们更好地回答您的问题。
  • 欢迎来到 StackOverflow! 我们不是代码编写服务。请向我们展示您尝试过的内容,并详细说明问题所在。另外,请学习 how to ask 好问题以获得更多提示。

标签: php regex preg-match-all substring


【解决方案1】:

# 符号之后使用否定字符类以获得最高的模式效率:

模式:(Demo)

#[^ ]+  #this will match the hashtag then one or more non-space characters.

代码:(Demo)

$in='one #two three #four #five';
var_export(preg_match_all('/#[^ ]+/',$in,$out)?$out[0]:'failed');  // access [0] of result

输出:

array (
  0 => '#two',
  1 => '#four',
  2 => '#five',
)

【讨论】:

    【解决方案2】:

    试试这个:

    $text="one #two three #four #five";
    $parts = array_filter(
        explode(' ', $text), // split into words
        function($word) {
            // filter out all that don't start with '#' by keeping all that do
            return strpos($word,"#")===0; 
            // returns true when the word starts with "#", false otherwise
        }  
    );
    print_r($parts);
    

    你可以在这里看到它:https://3v4l.org/YBnu3

    您可能还想阅读array_filter

    【讨论】:

      【解决方案3】:

      尝试按以下方式拆分:\b #

      preg_split("/\\b #/", $text)
      

      【讨论】:

      • 感谢您的建议。我尝试了这段代码,但仍然得到结果数组([0] => 一 [1] => 二三 [2] => 四 [3] => 五)只需要#two,#four,#five。谢谢。
      猜你喜欢
      • 1970-01-01
      • 2018-11-16
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      相关资源
      最近更新 更多