I have some text with twitter style #hashtags. How would I write a function to parse a body of text that might contain an unlimited number of #hashtags, take the text of the hashtag and replace them all with an <a href="tag/[hashtag text]">[hashtag text]</a>
I've thought a lot about how to do this but I am really bad at writing these sorts of functions with regex.
Example text:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus #tristique non elit eu iaculis. Vivamus eget ultricies nisi. Vivamus hendrerit at mauris condimentum scelerisque. Donec nibh mauris, pulvinar et #commodo a, porta et tellus. Duis eget ante gravida, convallis augue id, blandit lectus. Mauris euismod commodo mi ut fringilla. Sed felis magna, rhoncus vitae mattis varius, sagittis a eros. Donec eget porta ipsum. #Mauris sed mauris ante. Suspendisse potenti. Donec a #pretium #augue, eget hendrerit orci. Integer cursus scelerisque consequat.
Try using this:
$text = "Vivamus #tristique non elit eu iaculis.";
$text = preg_replace('/(?:^|\s)#(\w+)/', ' <a href="tag/$1">$1</a>', $text);
// $text now: Vivamus <a href="tag/tristique">tristique</a> non elit eu iaculis;
Here it is working: https://3v4l.org/WXqTr (click run).
Regex reference: Space or beginning of string, Non capturing group
Original source: Parsing Twitter with RegExp
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