如何将字符串中的所有hasgtags都放入数组中?

时间:2015-07-29 09:57:45

标签: php arrays regex string hashtag

我需要将用户输入的哈希标记作为数组。

输入:

$str = "hello#new #test #again"

预期产出:

Array ( [0] => new [1] => test [2] => again )

我尝试过这段代码,但它没有按预期工作:

function convertHashtags($str){
    $regex = "/#+([a-zA-Z0-9_]+)/";
    $str = preg_replace($regex, '<a href="hashtag.php?tag=$1">$0</a>', $str);
    return($str);    
}

$string = "hello#new #test #again";
$string = convertHashtags($string);

而不是替换我需要$string标签作为数组。

5 个答案:

答案 0 :(得分:4)

这应该适合你:

首先使用str_replace()的空格替换所有#。然后,您可以简单地将其拆分为一个数组,其中preg_split()位于一个或多个空格(\s+)上。

<?php

    $string = "hello#new #test #again";
    $tags = preg_split("/\s+/", str_replace("#", " ", $string));

    print_r($tags);

?>

输出:

Array
(
    [0] => hello
    [1] => new
    [2] => test
    [3] => again
)

修改

如果你只想在数组中的hashtag之后的单词,只需使用:

<?php

    $string = "hello#new#test #again";
    preg_match_all("/#(\w+)/", $string, $m);

    print_r($m[1]);

?>

正则表达式解释:

#(\w+)
  • 匹配字符#realrally
  • \ w + 匹配任何字词 [a-zA-Z0-9 _]
    • 量词: + 在一次和无限次之间,尽可能多次,根据需要回馈[贪婪]

答案 1 :(得分:2)

试试这个正则表达式:

(#\S+)

Regex live here.

解释

( ' start of capturing-group # ' matches a sharp, meaning a new variable \S+ ' anything until next space ) ' and of capturing-group saving

希望它有所帮助。

答案 2 :(得分:0)

为什么要使用RegEx,如果没有必要?

您可以使用explode(),只要您只想将字符串拆分为#

$result = $explode('#',$string);

如果你想摆脱字符串中的,请使用以下内容:

foreach($result as $entrie){
  $entrie = trim($entrie):
}

这可以解决您的问题而无需使用RegEx。

修改

对于第一个元素没有#的部分,您可以使用它来处理它:

if(strpos($string,'#') === 0)unset($result[0]);

如果字符串中的第一个字符不是#

,则删除第一个entrie

答案 3 :(得分:0)

最简单的方法是

 $string = "hello#new #test #again";
 $result = explode('#',$string);
 array_shift($result);
 print_R($result);

答案 4 :(得分:0)

$list = []; 
$string = "hey hello #new #test #again"; 
$result = explode(' ',$string); 
foreach($result as $res) if (starts_with($res, '#')) $list[]=$res; 
print_r($list);