PHP - 如何获取以 # 开头的单词并从字符串中删除其他单词


PHP - How to get words starting with # and remove the others from string

$query = "Hello #world What's #up"
$newquery = "world, up"

所以基本上我不想删除不以#开头的单词

您可以在空格上拆分字符串并循环生成的数组,检查第一个字符是否为#。 像这样:

$bits = explode(' ', $query);
$newquery = array();
foreach($bits as $bit){
    if(strlen($bit) > 0 && $bit[0] === '#') $newquery[] = $bit;
}
$newquery = implode(', ', $newquery);

您还可以使用正则表达式(如 (?:'#([^'s]+))(来获取匹配的单词。

编辑:正如Scopey指出的那样,我的初始正则表达式可以改进(在下面更改(,您应该使用$matches[1],因为返回的数组是多维的。请参阅:http://php.net/manual/en/function.preg-match-all.php

这可能看起来像这样:

preg_match_all('/#([^#'s]+)/', $query, $matches);
$newquery = implode(', ', $matches[1]);