How do I extract words starting with a hash tag (#) from a string into an array

无人久伴 提交于 2019-11-27 03:30:57

问题


I have a string that has hash tags in it and I'm trying to pull the tags out I think i'm pretty close but getting a multi-dimensional array with the same results

  $string = "this is #a string with #some sweet #hash tags";

     preg_match_all('/(?!\b)(#\w+\b)/',$string,$matches);

     print_r($matches);

which yields

 Array ( 
    [0] => Array ( 
        [0] => "#a" 
        [1] => "#some"
        [2] => "#hash" 
    ) 
    [1] => Array ( 
        [0] => "#a"
        [1] => "#some"
        [2] => "#hash"
    )
)

I just want one array with each word beginning with a hash tag.


回答1:


this can be done by the /(?<!\w)#\w+/ regx it will work




回答2:


That's what preg_match_all does. You always get a multidimensional array. [0] is the complete match and [1] the first capture groups result list.

Just access $matches[1] for the desired strings. (Your dump with the depicted extraneous Array ( [0] => Array ( [0] was incorrect. You get one subarray level.)




回答3:


I think this function will help you:

echo get_hashtags($string);

function get_hashtags($string, $str = 1) {
    preg_match_all('/#(\w+)/',$string,$matches);
    $i = 0;
    if ($str) {
        foreach ($matches[1] as $match) {
            $count = count($matches[1]);
            $keywords .= "$match";
            $i++;
            if ($count > $i) $keywords .= ", ";
        }
    } else {
        foreach ($matches[1] as $match) {
            $keyword[] = $match;
        }
        $keywords = $keyword;
    }
    return $keywords;
}



回答4:


Try:

$string = "this is #a string with #some sweet #hash tags";
preg_match_all('/(?<!\w)#\S+/', $string, $matches);
print_r($matches[0]);
echo("<br><br>");

// Output: Array ( [0] => #a [1] => #some [2] => #hash )


来源:https://stackoverflow.com/questions/13639478/how-do-i-extract-words-starting-with-a-hash-tag-from-a-string-into-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!