2013-03-21 75 views
3

我使用这个:正则表达式没有空格提取哈希标签

$t = "#hashtag #goodhash_tag united states #l33t this"; 
$queryVariable = ""; 
if(preg_match_all('/(^|\s)(#\w+)/', $t, $arrHashTags) > 0){ 
    array_filter($arrHashTags); 
    array_unique($arrHashTags); 
    $count = count($arrHashTags[2]); 
    if($count > 1){ 
     $counter = 1; 
     foreach ($arrHashTags[2] as $strHashTag) { 
      if (preg_match('/#\d*[a-z_]+/i', $strHashTag)) { 
       if($counter == $count){ 
        $queryVariable .= $strHashTag;    
       } else{ 
        $queryVariable .= $strHashTag." and "; 
       } 
       $newTest = str_replace($arrHashTags[2],"", $t);     
      } 
      $counter = $counter + 1; 
     } 
    } 
} 
echo $queryVariable."<br>"; // this is list of tags 
echo $newTest; // this is the remaining text 

基于上述$t的输出是:

#hashtag and #goodhash_tag and #l33t 
united states this 

第一个问题:

如果$t = '#hashtag#goodhash_tag united states #l33t this';即不两个标记之间的空间,输出变为:

#hashtag and #l33t 
#goodhash_tag united states this 

问题二:

如果$t = '#hashtag #goodhash_tag united states #l33t this #123';即具有无效标签#123它在某种程度上扰乱了我的标签列表中$queryVariable提取等的输出变得若有人在这两个

#hashtag and #goodhash_tag and #l33t and // note the extra 'and' 
united states this 

请帮助?

+0

我会很感激,如果有人可以帮助莫名其妙除了upvoting问题:) – coder101 2013-03-21 06:27:24

+0

一个小的建议是使用'(#A-Z _] \ w +)'代替。 =) – hjpotter92 2013-03-21 06:29:52

+0

@DreamEater你的意思是说,在'preg_match'被使用的那一行,你想让我替换整个模式还是其中的一部分? – coder101 2013-03-21 06:31:41

回答

5

而不是使用这么多comparisions等,为您的正则表达式。您只需具备以下条件:

$t = "#hashtag #goodhash_tag united states #l33t this #123#tte#anothertag sth"; 
$queryVariable = ""; 
preg_match_all('/(#[A-z_]\w+)/', $t, $arrHashTags); 
print_r($arrHashTags[1]); 

为了让他们作为字符串and加入他们,你可以使用破灭。

$queryVariable = implode($arrHashTags[1], " and "); 

对于剩下的文字,你可以有preg_replacestr_replace(无论你是舒服)。


这是codepad link

+0

实现我所有的需求,谢谢你。我有一个问题,但你确定我所做的所有比较将由你建议的代码来处理吗? – coder101 2013-03-21 07:10:35

+0

@ coder101除了'array_unique'部分,是的。您也可以添加该功能。 – hjpotter92 2013-03-21 07:13:46

+0

你怎么看'array_filter',过滤掉任何空值? – coder101 2013-03-21 07:14:41