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?
Hope this will help you out.
Regex demo
Regex: #[^\s]+|(?<=\s|^)@[^\s@#]+
1.
#[^\s]+this will match#and then match all tillspace(not including space)2.
|or3.
(?<=\s|^)@[^\s@#]+match@and thenallexceptspace,@and#with positive look behind forspaceorstart 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With