TwitterFacebook

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

Expressions that are regular
LGF • Views: 8,752
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.

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

^ back to top ^

TwitterFacebook

Turn off all ads for a full year by subscribing!
For about 33 cents a day (per month) or 22 cents a day (per year), our subscription option turns off all advertisements at LGF!
Read more...

► LGF Headlines

  • Loading...

► Tweeted Articles

  • Loading...

► Tweeted Pages

  • Loading...

► Top 10 Comments

  • Loading...

► Bottom Comments

  • Loading...

► Recent Comments

  • Loading...

► Tools/Info

► Tag Cloud

► Contact

You must have Javascript enabled to use the contact form.
Your email:

Subject:

Message:


Messages may be published unless you request otherwise.
Tech Note:
Using the Contact Form
LGF Pages

This button leads to the main index of LGF Pages, our user-submitted articles. You can post your own LGF Pages simply by registering a free account with us.

Create a Page

This 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: 2014-03-07 2:19 pm PST

LGF User's Guide
Recent Pages
Rightwingconspirator
A Lizard’s Regenerating Tail
Don't ya hate it when that happens? You feel so short for a month. Anoles are curious little lizards capable of ditching their tails when they feel threatened. This self-amputation, called autotomy, takes about 25 days for the tail to ...

32 minutes ago
Views: 33 • Comments: 0
Tweets: 0 • Rating: 0
CriticalDragon1177
Io9 - Everything You Need To Know About Lemuria, The Lost Continent Of Lemurs
Esther Inglis-Arkell talks about the weirdest lost continent myth, I've ever heard. Its the only one I know of that ever included giant telepathic lemurs. No seriously! In 1858 a young zoologist, playing around with an idea, came up with ...

2 hours, 15 minutes ago
Views: 73 • Comments: 0
Tweets: 0 • Rating: 2
Randall Gross
U.S. Accuses Israel Police of Targeting Slain Palestinian Boy’s Family
The U.S. State Department on Wednesday accused Israel of having "singled out" for arrest members of the family of Mohammed Abu Khdeir, the Palestinian boy who was burned alive last month by Israeli Jews. The statement followed the arrest ...

5 hours, 27 minutes ago
Views: 244 • Comments: 0
Tweets: 10 • Rating: 0
FemNaziBitch
Face It: The Abortion Battle Is Just About Sex- US News
The phony battle over certain kinds of birth control that are (often wrongly) called abortifacients is not about abortion. And much of the political fight about abortion isn't really about abortion, either. It's about whether women should be allowed ...

9 hours, 55 minutes ago
Views: 149 • Comments: 0
Tweets: 0 • Rating: 0
Laughing Gas
Scumbag “HBD believer” claims Michael Brown charged officer
WARNING: LINK TO HATE SITE He links to some ijreview, a right wing site: This guy makes me sick.

3 days, 1 hour ago
Views: 657 • Comments: 6
Tweets: 1 • Rating: 0
BadExampleMan
“Growth” and Some Jellyfish
This piece was basically just to use up some scraps I had sitting around. I liked the way the frit lace turned out but I didn't really have a use for it. I've been on a jellyfish kick lately. This ...

6 days, 15 hours ago
Views: 330 • Comments: 0
Tweets: 1 • Rating: 2
Pie-onist Overlord
Police Investigating Whether Rabbi’s Miami Killing a Hate Crime
More: Police Investigating Whether Rabbi's Miami Killing a Hate Crime (Reuters) - Police in Miami investigating the killing of a 60-year-old Orthodox rabbi over the weekend said on Monday they haven't yet decided whether the shooting was a hate crime. ...

1 week, 2 days ago
Views: 566 • Comments: 0
Tweets: 1 • Rating: 1
Romantic Heretic
The War Photo No One Would Publish
An interesting story on a photograph taken during Desert Storm that no news outlet in the US would publish. It is one of those photos that stares straight at the horror of war. It's hideous, stomach turning...and something that should ...

1 week, 5 days ago
Views: 1,336 • Comments: 8
Tweets: 4 • Rating: 7
 Frank says:

Always get a second opinion. -- His personal physician did not diagnose prostate cancer before it was too advanced to treat with any success.