Detect a link

Posted on 2000-01-05
Medium Priority
Last Modified: 2010-03-05
How can I detect a link in a string and surround that link with the <a href> tag?

For example:

$str = "visit my site at http://www.something.com or http://www.somethingelse.com";

I would then want that to become

$str = "visit my site at <a href=\"http://www.something.com\">http://www.something.com</a> or <a href=\"http://www.somethingelse.com\">http://www.somethingelse.com</a>";

Im thinking of using regular expressions, but I dont know how to go about it.

Question by:blokey
LVL 25

Expert Comment

ID: 2327823
$str =~ s#(http://\S+)#<a href="$1">$1</a>#ig;

print $str;

Accepted Solution

maxkir earned 200 total points
ID: 2328791

# Add http:// before www., if needed
$str =~ s#\bwww\.#http://www.#gi;

# Add ftp:// before ftp., if needed
$str =~ s#\bftp\.#ftp://ftp.#gi;

# Make <A HREF
# Works for http:// and ftp://
$str =~ s#(h?[tf]tp://[\.\w%&=]+)#<A HREF="$1">$1</A>#gi;

Expert Comment

ID: 3230196
The accepted answer only creates a link for the domain name not the entire URL, How can we fix that?

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
Article by: Tammy
MySQLTuner is a script written in Perl that allows you to review a MySQL installation quickly and make adjustments to increase performance and stability. The current configuration variables and status data is retrieved and presented in a brief forma…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans

600 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question