<分区>
我有这句话
"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?
这不是我的灵魂所渴望的
<分区>
我有这句话
"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()
使用正则表达式查找字符串的目标部分。
preg_match("/#\w+/", $str, $matches);
echo $matches[0]
检查demo中代码的结果
如果你想得到所有匹配的字符串,使用preg_match_all()
找到所有匹配项。
preg_match_all("/#\w+/", $str, $matches);
print_r($matches[0]);
关于php - 如何使用php获取字符串中以 '#'开头的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40441603/