问题描述
开头的所有单词的列表
$string = "Hello @bablu,This is my friend @roshan. Say hi to all. Also,I introduce 1 friend that is [email protected]."
现在在此字符串中,我只需要获取bablu和roshan 。由于amit有电子邮件地址,因此无法获取[email protected]。现在,我已经从 @ 中爆炸,但是爆炸方法也拆分了电子邮件地址。
$explode = explode('@',$string);
print_r($explode);
我怎么只能在PHP中获得 @ 个单词?
[
0 => "",1 => "bablu",2 => "",3 => "roshan",4 => "amit",5 => "gmail.com"
]
我的例外答案是:
[
0 => "bablu",1 => "roshan"
]
解决方法
explode不执行任何操作,您只需要使用preg_match_all
$string = "Hello @bablu,This is my friend @roshan. Say hi to all. Also,I introduce 1 friend that is [email protected].";
preg_match_all('/\B@([a-zA-Z]+)/',$string,$matches);
print_r($matches[1]);
输出:
Array
(
[0] => bablu
[1] => roshan
)
\ B匹配空字符串,而不是单词的开头或结尾。因此,您可以忽略该电子邮件地址。
,可以做到这一点。
$explode = explode(' @',$string);
通过在@
之前添加空格