Tech Note: A Regular Expression to Convert Hashtags and Twitter Names to Links

Expressions that are regular
LGF • Views: 12,299
Image via Shutterstock

Once in a while I come up with a bit of code I think might be useful to others, and here’s the latest example: a regular expression that parses a string of text looking for Twitter hashtags (preceded with ‘#’) or usernames (preceded with ‘@’), and replaces them with HTML links to those pages at twitter.com. Every bit of text posted at LGF in a comment, page or article gets passed through this code.

It’s written in PHP, and uses preg_replace_callback() to process the matches with an anonymous function.

The regular expression is fairly sophisticated; named capturing groups are used to make it easier to reference the groups (instead of counting up parentheses), and it uses positive lookbehind combined with a lookaround conditional in order to avoid converting patterns that look like hashtags or usernames if they’re already contained within an HTML link.

Don’t panic, I won’t go into any more depth on the regular expression; I’ll leave that as an exercise for those who may be so inclined.

$text = preg_replace_callback(
	'~
		(?<=
			^
			|
			(?<=
				[^a-zA-Z0-9-.&]
			)
		)
		(?(?=
				]*>.+?
			)
			(?:
				]*>.+?
			)
			|
			(?
				[@#]{1}
			)
			(?
				[A-Za-z_]+[A-Za-z0-9_]+
			)
		)
	~xsi',
	function($matches) {
		if ($matches['name']) {
			return (
				'#' 
					: $matches['name'] . '/with_replies">@'
				) . $matches['name'] . ''
			);
		} else {
			return $matches[0];
		}
	},
	$text
);

Jump to bottom

55 comments
1 Kragar  Tue, Mar 25, 2014 3:17:37pm

So sorcery then?

2 Charles Johnson  Tue, Mar 25, 2014 3:18:20pm

Basically.

3 thedopefishlives  Tue, Mar 25, 2014 3:21:22pm

re: #1 Kragar

So sorcery then?

Any sufficiently advanced technology is indistinguishable from magic.

Then there’s regular expressions. I don’t even think God fully understands how those work. They’re the quantum physics of computer science.

4 Kragar  Tue, Mar 25, 2014 3:23:02pm

And I just realized my twitter friend from last thread was a molon labe twit

5 dog philosopher  Tue, Mar 25, 2014 3:24:13pm

but what if i’m irregular and expressionless?

6 dog philosopher  Tue, Mar 25, 2014 3:26:23pm

Once in a while I come up with a bit of code I think might be useful to others

the ‘stack overflow’ website denizens might like it if you post it there

7 thedopefishlives  Tue, Mar 25, 2014 3:27:40pm

re: #5 dog philosopher

but what if i’m irregular and expressionless?

There’s a pill for that.

8 Kragar  Tue, Mar 25, 2014 3:27:41pm

re: #5 dog philosopher

but what if i’m irregular and expressionless?

Try adding some fiber to your diet.

9 wrenchwench  Tue, Mar 25, 2014 3:33:18pm
preg_replace_callback()

Is that related to the Hobby Lobby case?

10 thedopefishlives  Tue, Mar 25, 2014 3:35:14pm

re: #9 wrenchwench

Is that related to the Hobby Lobby case?

Oh no you di’in’t!

11 darthstar  Tue, Mar 25, 2014 3:38:15pm

re: #1 Kragar

So sorcery then?

(waves dead chicken over laptop to fix bug)…damn. Doesn’t work.

12 darthstar  Tue, Mar 25, 2014 3:39:14pm

I’d use these, but I’m afraid I’d get pulled over for driving with them on.

13 Backwoods_Sleuth  Tue, Mar 25, 2014 3:39:20pm
14 CuriousLurker  Tue, Mar 25, 2014 3:40:25pm

Very useful—thanks, Charles.

re: #1 Kragar

So sorcery then?

re: #3 thedopefishlives

They’re the quantum physics of computer science.

Regex = Voodoo

15 darthstar  Tue, Mar 25, 2014 3:41:50pm

re: #13 Backwoods_Sleuth

[Embedded content]

What a jackass.

16 CuriousLurker  Tue, Mar 25, 2014 3:44:56pm

re: #11 darthstar

(waves dead chicken over laptop to fix bug)…damn. Doesn’t work.

You have do it at the stroke of midnight and kill the chicken afterwards. //

17 dog philosopher  Tue, Mar 25, 2014 3:45:13pm

regex challenge

(they gave us this one when i was studying computer science back during the hundred years war)

write a regular expression that will detect any palindrome

18 thedopefishlives  Tue, Mar 25, 2014 3:45:18pm

re: #14 CuriousLurker

Regex = Voodoo

In my life, I have written many regexes.

I apologize for them all.

19 Targetpractice  Tue, Mar 25, 2014 3:46:05pm

re: #12 darthstar

I’d use these, but I’m afraid I’d get pulled over for driving with them on.

[Embedded content]

Knowing me, I’d play a game like Skyrim with one of these, run into a giant spider, and spend the next hour huddled in a corner and whimpering.

20 Targetpractice  Tue, Mar 25, 2014 3:57:20pm

I’ve killed another thread. Two more this week and I’ll be an ace.

21 darthstar  Tue, Mar 25, 2014 3:58:30pm
22 darthstar  Tue, Mar 25, 2014 3:59:44pm
23 Lidane  Tue, Mar 25, 2014 3:59:46pm
24 thedopefishlives  Tue, Mar 25, 2014 4:00:39pm

re: #20 Targetpractice

I’ve killed another thread. Two more this week and I’ll be an ace.

Do you draw a little green football on your keyboard for each one?

25 Justanotherhuman  Tue, Mar 25, 2014 4:06:20pm

Mark Z getting scared.

“I’m king of the world!”

No, you’re a little shit who got lucky by kissing the right asses.

26 dog philosopher  Tue, Mar 25, 2014 4:09:21pm

re: #25 Justanotherhuman

Mark Z getting scared.

“I’m king of the world!”

No, you’re a little shit who got lucky by kissing the right asses.

there was a chart somewhere showing the rise and fall of social networking sites

it showed fb as now on the shady side of the hill

27 Targetpractice  Tue, Mar 25, 2014 4:10:43pm

re: #24 thedopefishlives

Do you draw a little green football on your keyboard for each one?

Nah, I cut out a stencil and just use it to paint “kill” marks.

28 CuriousLurker  Tue, Mar 25, 2014 4:10:54pm

re: #16 CuriousLurker

You have do it at the stroke of midnight and kill the chicken afterwards. //

What is it with chickens, eggs, and magic anyway?

Some Mexicans believe in a kind of superstitious folk medicine—maybe it would be more accurately called shamanism as these things are also performed by curanderos—where a raw egg is used to draw out illness by rubbing it over the sick person’s body, then placing it under their bed for a period of time, and finally disposing of it in water.

My grandma did it to me once, when I was little and got really sick while staying at her house. I don’t remember all the details, but I think Catholic prayers were also included. When my dad, an agnostic, learned of it he was positively livid.

It was very odd to read about a similar practice in Carlos Castaneda’s The Teachings of Don Juan (at least I think it was that book, but it could have been one of his others as I read more than one).

29 Kid A  Tue, Mar 25, 2014 4:11:40pm

Just curious- Why aren’t the cockpit recorders of airliners digitized, or sent to some kind of hard drive backup, a cloud, etc so we don’t have to comb the ocean floor for the flight recorders?

30 Killgore Trout  Tue, Mar 25, 2014 4:12:19pm

This Is a Generic Brand Video
Youtube Video

31 RealityBasedSteve  Tue, Mar 25, 2014 4:13:10pm

I’ve got a sadz. My very favorite circulon pan, the one that has fixed my dinner for 15 years, has developed a chunk in that broke lose. I’ve never abused it, so I probably got the 25-30 bucks that it cost me off of eBay. Circulon doesn’t make that model any more, and now I’ve got to try and track down a replacement. I’m going to send it in, see if I can get a claim under their limited lifetime warranty, but I’m not too confident.

RBS

32 wrenchwench  Tue, Mar 25, 2014 4:14:22pm

Jumpin’ Jesus! Jumping off of Jesus, actually.

33 dog philosopher  Tue, Mar 25, 2014 4:14:24pm

re: #29 Kid A

Just curious- Why aren’t the cockpit recorders of airliners digitized, or sent to some kind of hard drive backup, a cloud, etc so we don’t have to comb the ocean floor for the flight recorders?

cost vis-a-vis bandwidth of information

also, com coverage where you might be flying

34 CuriousLurker  Tue, Mar 25, 2014 4:15:28pm

re: #31 RealityBasedSteve

Circulon makes some good pans. It’s worth a shot to see if you can get a replacement. AFter all, the worst that can happen is they say, “No.”

36 Justanotherhuman  Tue, Mar 25, 2014 4:17:42pm

I hope this isn’t a “thing” among kids. The guy looks like a young Snowden.

Revealed: Hateful suicide notes left by police killers Alexandria Hollinghurst and Brandon Goode

metro.co.uk

37 RealityBasedSteve  Tue, Mar 25, 2014 4:17:48pm

re: #29 Kid A

Just curious- Why aren’t the cockpit recorders of airliners digitized, or sent to some kind of hard drive backup, a cloud, etc so we don’t have to comb the ocean floor for the flight recorders?

I wouldn’t be surprised if that doesn’t get implemented sometime in the not-distant future. That and and a series of location updates via GPS (maybe at 5 minute intervals). Even if they didn’t send ALL the data tracked by the FDRs, I’m sure that there are a set of KEY values that could be sent that would provide at least sufficient info to start to resolve problems.

RBS

38 Backwoods_Sleuth  Tue, Mar 25, 2014 4:18:50pm

or maybe it’s more bats…

39 Backwoods_Sleuth  Tue, Mar 25, 2014 4:20:28pm

re: #38 Backwoods_Sleuth

OTOH, it’s really a haboob.

40 Amory Blaine  Tue, Mar 25, 2014 4:21:16pm
41 Backwoods_Sleuth  Tue, Mar 25, 2014 4:21:43pm
42 wrenchwench  Tue, Mar 25, 2014 4:23:41pm

re: #39 Backwoods_Sleuth

OTOH, it’s really a haboob.

[Embedded content]

Yikes. We’re supposed to get a little rain tonight, which is the only thing that might stop an Arizona haboob from drifting into New Mexico.

43 CuriousLurker  Tue, Mar 25, 2014 4:26:21pm

re: #28 CuriousLurker

What is it with chickens, eggs, and magic anyway?

Some Mexicans believe in a kind of superstitious folk medicine—maybe it would be more accurately called shamanism as these things are also performed by curanderos—where a raw egg is used to draw out illness by rubbing it over the sick person’s body, then placing it under their bed for a period of time, and finally disposing of it in water.

My grandma did it to me once, when I was little and got really sick while staying at her house. I don’t remember all the details, but I think Catholic prayers were also included. When my dad, an agnostic, learned of it he was positively livid.

It was very odd to read about a similar practice in Carlos Castaneda’s The Teachings of Don Juan (at least I think it was that book, but it could have been one of his others as I read more than one).

Ah, here we go: Tricks About Egg Cleansings

Aztec shamans performing a spiritual cleansing ritual in the Zocalo on January 17, 2009 in Mexico City, Mexico.

Getty Image

Getty Image

44 dog philosopher  Tue, Mar 25, 2014 4:26:56pm

re: #40 Amory Blaine

Classical Guitar Tablature

bookmarked!

45 CuriousLurker  Tue, Mar 25, 2014 4:27:53pm

re: #39 Backwoods_Sleuth

OTOH, it’s really a haboob.

[Embedded content]

re: #42 wrenchwench

Yikes. We’re supposed to get a little rain tonight, which is the only thing that might stop an Arizona haboob from drifting into New Mexico.

Stop saying HABOOB!!11!

46 dog philosopher  Tue, Mar 25, 2014 4:29:38pm

re: #43 CuriousLurker

Zocalo

the word is common in spanish with the meaning of town square, but derives ultimately from a word meaning ‘plinth’ - presumably in town squares there might be a statue standing on a plinth

curiously, the word exists in english dictionaries, as ‘socle’, but of course who ever even heard of it?

47 Kid A  Tue, Mar 25, 2014 4:30:06pm
48 CuriousLurker  Tue, Mar 25, 2014 4:32:12pm

Sooooo…. Y’all wanna do a drum circle, then we can sing Kumbaya and perform some egg cleansing rituals on each other? Anyone? //

49 Kid A  Tue, Mar 25, 2014 4:32:35pm

Watch your backgrounds, please.

50 darthstar  Tue, Mar 25, 2014 4:33:01pm

re: #42 wrenchwench

Yikes. We’re supposed to get a little rain tonight, which is the only thing that might stop an Arizona haboob from drifting into New Mexico.

STOP CALLING IT A HABOOB!

I’m such a haboob.

51 CuriousLurker  Tue, Mar 25, 2014 4:34:16pm

re: #46 dog philosopher

the word is common in spanish with the meaning of town square, but derives ultimately from a word meaning ‘plinth’ - presumably in town squares there might be a statue standing on a plinth

curiously, the word exists in english dictionaries, as ‘socle’, but of course who ever even heard of it?

That’s interesting, thanks.

52 Stanley Sea  Tue, Mar 25, 2014 4:35:27pm

That haboob had better not f with my flight!!!

53 b_sharp  Tue, Mar 25, 2014 4:35:52pm

re: #28 CuriousLurker

What is it with chickens, eggs, and magic anyway?

Some Mexicans believe in a kind of superstitious folk medicine—maybe it would be more accurately called shamanism as these things are also performed by curanderos—where a raw egg is used to draw out illness by rubbing it over the sick person’s body, then placing it under their bed for a period of time, and finally disposing of it in water.

My grandma did it to me once, when I was little and got really sick while staying at her house. I don’t remember all the details, but I think Catholic prayers were also included. When my dad, an agnostic, learned of it he was positively livid.

It was very odd to read about a similar practice in Carlos Castaneda’s The Teachings of Don Juan (at least I think it was that book, but it could have been one of his others as I read more than one).

I read far too many of Castaneda’s books back in the ’70s.

54 b.d.  Tue, Mar 25, 2014 4:36:21pm

NO MORE SHARIA STORMS OBAMA!!

55 RealityBasedSteve  Tue, Mar 25, 2014 4:36:22pm

re: #45 CuriousLurker

Stop saying HABOOB!!11!

HaBoobies!!!! Ehh Ehh Ehh…

RBS


This article has been archived.
Comments are closed.

Jump to top

Create a PageThis is the LGF Pages posting bookmarklet. To use it, drag this button to your browser's bookmark bar, and title it 'LGF Pages' (or whatever you like). Then browse to a site you want to post, select some text on the page to use for a quote, click the bookmarklet, and the Pages posting window will appear with the title, text, and any embedded video or audio files already filled in, ready to go.
Or... you can just click this button to open the Pages posting window right away.
Last updated: 2023-04-04 11:11 am PDT
LGF User's Guide RSS Feeds

Help support Little Green Footballs!

Subscribe now for ad-free access!Register and sign in to a free LGF account before subscribing, and your ad-free access will be automatically enabled.

Donate with
PayPal
Cash.app
Recent PagesClick to refresh
The Pandemic Cost 7 Million Lives, but Talks to Prevent a Repeat Stall In late 2021, as the world reeled from the arrival of the highly contagious omicron variant of the coronavirus, representatives of almost 200 countries met - some online, some in-person in Geneva - hoping to forestall a future worldwide ...
Cheechako
Yesterday
Views: 77 • Comments: 0 • Rating: 1
Texas County at Center of Border Fight Is Overwhelmed by Migrant Deaths EAGLE PASS, Tex. - The undertaker lighted a cigarette and held it between his latex-gloved fingers as he stood over the bloated body bag lying in the bed of his battered pickup truck. The woman had been fished out ...
Cheechako
2 weeks ago
Views: 249 • Comments: 0 • Rating: 1