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

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

For example:

$longstring = "blah blah blah #hashtag blah blah @twittername blah email@email.com blah blah #hashtag2 blah blah";

      

And I want to create one new line:

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

      

Any idea how I can do this easily?

I'm not sure if the answer is a regular expression? Can it do this together and find all multiple occurrences of both types?

+3


source to share


3 answers


preg_match_all

decision:

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

print_r($extracted);

      



Output:

#hashtag @twittername #hashtag2

      

+3


source


Hope this helps you.

Demo Regex

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

1.this #[^\s]+

will match #

and then match everything before space

(not including the space)

2. |

or

3. (?<=\s|^)@[^\s@#]+

coincidence @

, then all

apart space

, @

and #

with a positive outlook for space

orstart of string



Here we use preg_match_all

to collect matches and implode

to attach to it as a string.

Try this piece of code here

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

      

Output: #hashtag @twittername #hashtag2

+3


source


The following code will work for you: Here, we first split the sentence into spaces.

Then we check that the word starts with "@" or "#".

If so, add it to a new line.

<?php
function startsWith($haystack, $needle)
{
    return strpos($haystack, $needle) === 0;
}
$longstring = "blah blah blah #hashtag blah blah @twittername blah email@email.com blah blah #hashtag2 blah blah";
$parts = explode(" ",$longstring);
$newString = "";
foreach($parts as $part)
{
    if(startsWith($part, "#") || startsWith($part, "@"))
    {
        $newString.= $part." ";
    }
}

echo $newString;

      

+3


source







All Articles