Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse text for hashtags and replace with links using php

Tags:

regex

php

tags

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.

like image 861
Amy Neville Avatar asked Jun 21 '13 22:06

Amy Neville


1 Answers

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

like image 150
Joe Avatar answered Oct 28 '22 02:10

Joe