Reputation: 1110
I am trying to find all the hashtags in a String
Example String:
Hello World #Hello #World #Hello-World #Hello_World #Test-Tag
I tried using below code:
preg_match_all('/#([^\s]+)/', $postbody, $matches);
$tags = implode(',', $matches[1]);
var_dump($tags);
The result is
Hello,World,Hello-World,Hello_World,Test-Tag
How can I make it end at any characters besides A-Z, a-z, and 0-9
My goal output is
Hello, World, Test
I would like it to stop right before it reaches a character that isn't a letter or number also not print duplicates.
Reference: Get hashtag from string reference
Upvotes: 0
Views: 375
Reputation: 1791
You can use [a-zA-Z0-9]
regex to get only letters and numbers.
And later, use array_unique to filter out duplicate matches
$postbody = 'Hello World #Hello #World #Hello-World #Hello_World #Test-Tag';
preg_match_all('/#([a-zA-Z0-9]+)/', $postbody, $matches);
if(!empty($matches)){
$tags = implode(',', array_unique($matches[1]));
var_dump($tags);
}
Output: string(16) "Hello,World,Test"
Upvotes: 1