Check whether a string contains a URL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
implications
Forum Commoner
Posts: 25
Joined: Thu Apr 07, 2011 3:59 am

Check whether a string contains a URL

Post by implications »

I'm trying to set this up so that if regex matches a URL in the string of text, it will turn that URL into an active link.

Code: Select all

<?php
$text = "What's up man this is the link to the page: http://google.com";
if (ereg('^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$',$text)) {
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $text);
}
echo "$text";
?>
The way my current code is set up, it doesn't work. How do I make PHP detect whether there is a URL present in a chunk of text?
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Check whether a string contains a URL

Post by social_experiment »

Try using preg_match() instead, similar to the code you pasted, if a match exists, wrap it in the anchor tags
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply