I have a string that contains text, and in several places there will be a twitter-style hashtag. I want to find them and create a seperate variable where all of them are seperated by spaces. I also want to convert all of the hashtags in the original string into links. Example:
$string = "Hello. This is a #hashtag and this is yet another #hashtag. This is #another #example."
after function:
$string_f = "Hello this is a <a href='#'>#hashtag</a> and this is yet another <a href='#'>#hashtag</a>. This is <a href='#'>another</a> <a href='#'>example</a>";
$tags = '#hashtag #another #example';
To find all of the hash tags, use a regex and
preg_match_all(), and do the replacement withpreg_replace():Then all of the tags are in an array in
$matches[1]:Then, convert that to a space-separated list with
implode()andarray_unique():And you’re done. You can see from this demo that
$tagsand$string_fare:For other characters in the hashtag (for example, digits), modify the
$regexappropriately.Edit: However, this can be improved in efficiency if you use
preg_replace_callback()and a closure so you only have to execute the regex once, like so: