How to extract words starting with a hash tag (#) from a string to an array

I have a line that has hash tags and I'm trying to pull tags. I think I'm pretty close, but getting a multidimensional 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); 

what gives

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

I just need one array with every word starting with a hash tag.

+7
source share
4 answers

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

+14
source

What does preg_match_all do. You always get a multidimensional array. [0] is a complete match and [1] first list of capture group results.

Just select $matches[1] for the desired lines. (Your dump with an extraneous Array ( [0] => Array ( [0] depicted Array ( [0] => Array ( [0] was wrong. You have one submarine level.)

+3
source

I think this feature 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; } 
+2
source

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 ) 
0
source

All Articles