我有这句话如何获得以字符串开头的单词使用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?
这是不是我的灵魂渴望
我有这句话如何获得以字符串开头的单词使用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?
这是不是我的灵魂渴望
有简单的解决办法做到这一点。使用preg_match()
使用正则表达式找到字符串的目标部分。的代码demo
如果你想获得的所有相匹配的字符串,使用preg_match_all()
即找到所有匹配
preg_match("/#\w+/", $str, $matches);
echo $matches[0]
检查结果。
preg_match_all("/#\w+/", $str, $matches);
print_r($matches[0]);
个人而言,我不会与#
捕捉这个词,因为哈希标签是唯一的标识符为您的代码,以获得附加字。
$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)'可以替换为'(?<!\ S)' –
@CasimiretHippolyte我真的没有想到使用负面的后视,很好的捕捉。 – Xorifelse
如果有两个'#'怎么办?我试过'echo $ matches [$ i];'但没有奏效。 – Papaa
尝试:'var_dump($ matches)'来查看结果的样子。 –
@MagnusEriksson一句话:'#Save #thy#selves'。结果:'array(1){[0] => string(5)“#Save”}' – Papaa