Hi all

I'm trying to find any urls inside a paragraph of text pulled from a db and wrap an a tag around it. At the moment I have the following which isn't working.

$content = $row[2];
$urlStart = strstr($content, "http://");
$url_http = substr($urlStart, 0, strpos(array($urlStart), array(" ", "/r/n", "/r", "/n")));
$url_plain = str_replace(array("http://"), array(""), $url_http);
$url_name = substr($url_plain, 0, 40);
if (strlen($url_plain) >= 40)
{
$text = str_replace(array($url_http), array("<a class='diaryUrl' target='_blank' href=".$url_http." >".$url_name."</a>"), $content);
} else {
$text = str_replace(array($url_http), array("<a class='diaryUrl' target='_blank' href=".$url_http." >".$url_plain."</a>"), $content);
}

Any help will be greatly appreciated

i found the following code which seems to work. Anyone know how to make the length of the text shown smaller ie. 40 chars instead of say 80.

$content = $row[2];
$text = preg_replace('@(http://[^\s]+)@sm', '<a class="diaryUrl" target="_blank" href="$1">$1</a>', $content);

Something like this should work:

<?php
$content="http://www.daniweb.com/forums/thread135726.html";
$short=substr($content,0,22);
$text = preg_replace('@(http://[^\s]+)@sm', '<a class="diaryUrl" target="_blank" 

href="$1">'.$short.'</a>', $content);
echo $text;
?>

Hi buddy

Unfortunately that won't work for me as $content is a paragraph of text, not just a url.

is there a php function that will match all instances of a string? strstr only seems to match the first occurance.

Okay, what this does is it performs a substr on the text portion of the link only by using a function inside the preg_replace function:

<?php
$content="You can read more about reducing the text of the link at  http://www.daniweb.com/forums/thread135726.html .";
function reduceurl($url, $url_length) {
        $reduced_url = substr($url, 0, $url_length);
        if (strlen($url) > $url_length) {
		$reduced_url .= '...';
		return $reduced_url;
		}
	}
$text = preg_replace("@(http://[^\s]+)@sme", "'<a class=\"diaryUrl\" target=\"_blank\" href=\"$1\">' . reduceurl(\"$1\", 40) . '</a>'", $content);
echo $text;
?>

This will output "You can read more about reducing the text of the link at http://www.daniweb.com/forums/thread1357..." with the link in place.

commented: A great help. Thank you very much +1

Thanks for the help buddy. I had to modify your function a little bit but it helped a lot ;)

function reduceurl($url, $url_length) {
	if (strlen($url) > $url_length) {
	$reduced_url = substr($url, 7, $url_length);
	$reduced_url .= '...';
	return $reduced_url;
	} else {
	$reduced_url = substr($url, 7, strlen($url));
	return $reduced_url;
	}
}

It now displays the url without the http:// as well as limiting urls displayed with more than 40 characters

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.