【问题标题】:How to get the words that start with '#' in string using php? [duplicate]如何使用php获取字符串中以'#'开头的单词? [复制]
【发布时间】:2017-03-19 09:43:03
【问题描述】:

我有这句话

"My name's #jeff,what is thy name?"

现在我想从这句话中得到#jeff。 我试过这段代码

for ($i=0; $i <=substr_count($Text,'#'); $i++) { 
    $a=explode('#', $Text);
    echo $a[$i];
}

但它返回#jeff,what is thy name?,这不是我的灵魂所渴望的

【问题讨论】:

    标签: php regex string preg-match preg-match-all


    【解决方案1】:

    有更简单的解决方案。使用preg_match() 使用正则表达式查找字符串的目标部分。

    preg_match("/#\w+/", $str, $matches);
    echo $matches[0]
    

    检查demo中的代码结果

    如果要获取所有匹配字符串,请使用查找所有匹配项的preg_match_all()

    preg_match_all("/#\w+/", $str, $matches);
    print_r($matches[0]);
    

    【讨论】:

    • 如果有两个'#'怎么办?我试过echo $matches[$i];但没有用。
    • 试试:var_dump($matches) 看看结果如何。
    • @MagnusEriksson 句子:#Save #thy #selves。结果:array(1) { [0]=&gt; string(5) "#Save" }
    • preg_match() 在找到第一个匹配项后退出..
    • 如果字符串有多个匹配项,请使用preg_match_all()。见3v4l.org/GPjkc
    【解决方案2】:

    就我个人而言,我不会使用# 来捕获这个词,因为主题标签只是您的代码获取附加词的标识符。

    $re = '/(?<!\S)#([A-Za-z_][\w_]*)/';
    $str = "My name's #jeff,what #0is #thy name?";
    
    preg_match_all($re, $str, $matches);
    
    // Print the entire match result
    print_r($matches[0]); // #jeff, #thy
    print_r($matches[1]); // jeff, thy
    

    通过主题标签的rules,它可能不以数字开头,但可能包含它们。

    【讨论】:

    • 注意(?:^|\s)可以替换成(?&lt;!\S)
    • @CasimiretHippolyte 我真的没想过使用负面的后视,很好。
    猜你喜欢
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 2016-01-13
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多