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?
source to share
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
source to share
Hope this helps you.
Regex: #[^\s]+|(?<=\s|^)@[^\s@#]+
1.this
#[^\s]+
will match#
and then match everything beforespace
(not including the space)2.
|
or3.
(?<=\s|^)@[^\s@#]+
coincidence@
, thenall
apartspace
,@
and#
with a positive outlook forspace
orstart of string
Here we use preg_match_all
to collect matches and implode
to attach to it as a string.
<?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
source to share
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;
source to share