Pap*_*paa 3 php regex string preg-match-all preg-match
我有这句话
"My name's #jeff,what is thy name?"
Run Code Online (Sandbox Code Playgroud)
现在我想#jeff从这句话中得到。我已经尝试过这段代码
for ($i=0; $i <=substr_count($Text,'#'); $i++) {
$a=explode('#', $Text);
echo $a[$i];
}
Run Code Online (Sandbox Code Playgroud)
但它的回归#jeff,what is thy name?并不是我灵魂所渴望的
有更简单的解决方案可以做到这一点。使用preg_match()正则表达式查找字符串的目标部分。
preg_match("/#\w+/", $str, $matches);
echo $matches[0]
Run Code Online (Sandbox Code Playgroud)
检查demo中代码的结果
如果您想获取所有匹配字符串,请使用preg_match_all()查找所有匹配项。
preg_match_all("/#\w+/", $str, $matches);
print_r($matches[0]);
Run Code Online (Sandbox Code Playgroud)