Page 1 of 1

Check whether a string contains a URL

Posted: Tue Oct 18, 2011 6:44 am
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?

Re: Check whether a string contains a URL

Posted: Tue Oct 18, 2011 10:03 am
by social_experiment
Try using preg_match() instead, similar to the code you pasted, if a match exists, wrap it in the anchor tags