Q:

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 string.
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 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?

A:

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@email.com blah blah #hashtag2 blah blah";
preg_match_all("/#[^\s]+|(?<=\s|^)@[^\s@#]+/", $string, $matches);
print_r(implode(" ",$matches[0]));

Output:
#hashtag @twittername #hashtag2

A:

preg_match_all solution:
$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);

The output:
#hashtag @twittername #hashtag2

A:

The following code will work for you:
Here first we split the sentence by spaces.
Then we check is the word starts with an "@" or "#".
If yes then we append it to the new string.
<?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;

