Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php extract all hashtags and twitter names from a block of text

Tags:

php

I have a block of text in php, and I want to be able to extract all hashtags and twitter names from it, and print them as one new string.

For example:

$longstring = "blah blah blah #hashtag blah blah @twittername blah [email protected] blah blah #hashtag2 blah blah";

And I want to create one new string:

$extracted = "#hashtag @twittername #hashtag2";

Any idea how I can do this easily?

I'm not sure if the answer is a regex? Can that do both together and find all multiple occurrences of both types?

like image 663
R2D2 Avatar asked Feb 02 '26 16:02

R2D2


2 Answers

Hope this will help you out.

Regex demo

Regex: #[^\s]+|(?<=\s|^)@[^\s@#]+

1. #[^\s]+ this will match # and then match all till space(not including space)

2. | or

3. (?<=\s|^)@[^\s@#]+ match @ and then all except space, @ and # with positive look behind for space or start of string

Here we are using preg_match_all for gathering matches and implode for joining it as string.

Try this code snippet here

<?php
ini_set('display_errors', 1);
$string = "blah blah blah #hashtag blah blah @twittername blah [email protected] blah blah #hashtag2 blah blah";
preg_match_all("/#[^\s]+|(?<=\s|^)@[^\s@#]+/", $string, $matches);
print_r(implode(" ",$matches[0]));

Output: #hashtag @twittername #hashtag2

like image 62
Sahil Gulati Avatar answered Feb 05 '26 05:02

Sahil Gulati


preg_match_all solution:

$longstring = "blah blah blah #hashtag blah blah @twittername blah [email protected] blah blah #hashtag2 blah blah";
preg_match_all("/(?:^|\s)[#@][^ @#]+\b/", $longstring, $m);
$extracted = implode("", $m[0]);

print_r($extracted);

The output:

#hashtag @twittername #hashtag2
like image 24
RomanPerekhrest Avatar answered Feb 05 '26 05:02

RomanPerekhrest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!