2016-11-05 61 views
3

我有這句話如何獲得以字符串開頭的單詞使用PHP?

"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?這是不是我的靈魂渴望

回答

4

有簡單的解決辦法做到這一點。使用preg_match()使用正則表達式找到字符串的目標部分。的代碼demo

如果你想獲得的所有相匹配的字符串,使用preg_match_all()即找到所有匹配

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

檢查結果。

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

如果有兩個'#'怎麼辦?我試過'echo $ matches [$ i];'但沒有奏效。 – Papaa

+0

嘗試:'var_dump($ matches)'來查看結果的樣子。 –

+0

@MagnusEriksson一句話:'#Save #thy#selves'。結果:'array(1){[0] => string(5)「#Save」}' – Papaa

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,它可能無法以數字開頭,但可能包含它們。

+1

請注意'(?:^ | \ s)'可以替換爲'(?<!\ S)' –

+0

@CasimiretHippolyte我真的沒有想到使用負面的後視,很好的捕捉。 – Xorifelse

相關問題