Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 249
Brian Avatar asked Nov 30 '12 05:11

Brian


2 Answers

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

like image 90
NullPoiиteя Avatar answered Nov 05 '22 04:11

NullPoiиteя


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.)

like image 35
mario Avatar answered Nov 05 '22 03:11

mario