Skip to Content
Regular Expressions Cookbook
book

Regular Expressions Cookbook

by Jan Goyvaerts, Steven Levithan
May 2009
Intermediate to advanced
510 pages
15h
English
O'Reilly Media, Inc.
Content preview from Regular Expressions Cookbook

7.5. Turn URLs into Links

Problem

You have a body of text that may contain one or more URLs. You want to convert the URLs that it contains into links by placing HTML anchor tags around the URLs. The URL itself will be both the destination for the link and the text being linked.

Solution

To find the URLs in the text, use one of the regular expressions from Recipes 7.2 or 7.4. As the replacement text, use:

<ahref="$&">$&</a>
Replacement text flavors: .NET, JavaScript, Perl
<ahref="$0">$0</a>
Replacement text flavors: .NET, Java, PHP
<ahref="\0">\0</a>
Replacement text flavors: PHP, Ruby
<ahref="\&">\&</a>
Replacement text flavor: Ruby
<ahref="\g<0>">\g<0></a>
Replacement text flavor: Python

When programming, you can implement this search-and-replace as explained in Recipe 3.15.

Discussion

The solution to this problem is very straightforward. We use a regular expression to match a URL, and then replace it with «<ahref="URL">URL</a>», where URL represents the URL that we matched. Different programming languages use different syntax for the replacement text, hence the long list of solutions to this problem. But they all do exactly the same thing. Recipe 2.20 explains the replacement text syntax.

See Also

Recipes 2.21, 3.15, 7.2, and 7.4

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Regular Expressions Cookbook, 2nd Edition

Regular Expressions Cookbook, 2nd Edition

Jan Goyvaerts, Steven Levithan

Publisher Resources

ISBN: 9780596802837Catalog PageErrata