Hello, I am trying to find a way to make any URL's entered into the comments box on my site to automatically become linked and clickable after they are posted, without requiring the person entering the URL to enter any tags or HTML.

I came across a few tutorials, sort of, online and am having difficulty getting them to work for me. The comments are stored using a database. Here is my page code for the comments:

<?php

require($_SERVER['DOCUMENT_ROOT'].'/'.'init.php');

RequireLogin();




if($IsPostBack)
{
	if($_POST['post'] == 'Cancel')
	{
		$returnUrl = urldecode(Context::Current()->NextPage) . "#" . $drawing->Id;
		header("Location: " . urldecode($returnUrl));
		die;
	}

	$comment = $_POST['comment'];
	$drawingId = $_POST['DrawingId'];
	$drawing = Drawing::Load($drawingId);
	if(!empty($drawing))
	{
		if(!empty($comment))
		{
			$drawing->AddComment(Context::Current()->CurrentUser->Id, $comment);

			$returnUrl = urldecode(Context::Current()->NextPage) . "#" . $drawing->Id;
			header("Location: " . urldecode($returnUrl));
			die;
		}
		else
		{
			$ErrorMessage = "Comment cannot be empty.";
		}
	}
}
else
{
	$drawingId=0;

	if(isset($_GET['did']))
		if(ctype_digit($_GET['did']))
			$drawingId = $_GET['did'];

	if($drawingId == 0)
	{
		$returnUrl = $appRoot.'/index.php';
		header("Location: " . urldecode($returnUrl));
		die;
	}
	else if($drawingId > 0)
	{
		$drawing = Drawing::Load($drawingId);
		//Context::Current()->CurrentDrawing = $drawing;
	}
	else if(empty($drawing)){
		$returnUrl = $appRoot.'/index.php';
		header("Location: " . urldecode($returnUrl));
		die;
	}
}

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link type="text/css" rel="stylesheet" href="../styles/standard.css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Add Comment</title>
</head>
<body>

	<?php  showStandardHeader(false); ?>
	<div class="contentWrapper" >
		<div class="content">
			<div class="pageTitle">Add Comment</div>

			<?php if($ErrorMessage) { ?>

				<div style="color:red"><?php echo $ErrorMessage; ?></div>

			<?php } ?>

			<div class="boardItem">
		<div class="drawingTitleBar">

			<div class="drawingNumber"><?php echo "[" . $drawing->DrawingNumber . "]"; ?></div>
			<div class="drawingTitle">
				<?php echo $drawing->Title ? $drawing->Title : "Untitled"; ?>
				<?php echo " - by " ?>
				<?php CreateUserNameLinks($drawing->AllUserNames()); ?>
				<?php $time = $drawing->TotalTimeFormatted; if(!empty($time)) echo " - " . str_replace(" ", "&nbsp;", $drawing->TotalTimeFormatted); ?>
			</div>

			<div style="clear:both;"></div>
		</div>

		<div style="clear:both;border: #d1d1d1 dotted 1px;min-height:321px;min-heigh\t:324px;">
			<div class="boardImageCol" >
				<div style="padding:10px;margin:0;">
					<a href="<?php echo $appRoot . '/Drawing/viewDrawing.php?did=' . $drawing->Id; ?>">
						<img border="0" src="<?php echo $images_prefix . '/' . $drawing->Current->FilePath;?>" />
					</a>
				</div>

				<div class="boardIcons" style="clear: both;padding: 5px 5px 5px 10px;margin: 0;border-top-style:dotted;border-top-width:1px;border-top-color:#d1d1d1;">

					&nbsp;

        	</div><div style="clear:both;">
				</div>
			</div>

			<div class="boardCommentCol" >
				<form method=post action='index.php' id="login">
					<div style="padding:0 0 10px 0;"><textarea rows="10" cols="50" name="comment"></textarea></div>
					<div style="padding:0 0 10px 0;"><input name="post" type="submit" value="Post Comment" >&nbsp;&nbsp;&nbsp;<input name="post" type="submit" value="Cancel" ></div>

					<input name="IsPostBack" type="hidden" value="true">
					<input name="DrawingId" type="hidden" value="<?php echo $drawingId; ?>">
			</form>
				<div id="boardComments">
					<?php include($_SERVER['DOCUMENT_ROOT'] . $appRoot . '/' . 'Drawing/comments.php'); ?>
				</div>
			</div>
			<div style="clear:both;"></div>
		</div>

	</div>

		</div>	
		<div style="clear:both"></div>
	</div>
</body>
</html>

One tutorial suggested this code, I'm not certain how to implement it:

function makeClickableLinks($text)
{

    $text = html_entity_decode($text);
    $text = " ".$text;
    $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
            '<a href="\\1" target=_blank>\\1</a>', $text);
    $text = eregi_replace('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
            '<a href="\\1" target=_blank>\\1</a>', $text);
    $text = eregi_replace('([[:space:]()[{}])([url]www.[-a-zA-Z0-9@:%_\+.~#?&//=]+[/url])',
    '\\1<a href="http://\\2" target=_blank>\\2</a>', $text);
    $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
    '<a href="mailto:\\1" target=_blank>\\1</a>', $text);
    return $text;

}

// Example Usage
// echo makeClickableLinks("This is a test clickable link: http://www.websewak.com You can also try using an email address like test@websewak.com");

Others have suggessted using preg_replace. I am not clear on how to implement this, into my code.

    zorblon3;10916780 wrote:

    One tutorial suggested this code, I'm not certain how to implement it:

    its just a function so this should work:

    $comment = makeClickableLinks($_POST['comment']); 
    

      Thanks for the reply, where would I add that to the code I posted above (my page code)? I tried pasting it in several places, didn't seem to work.

      A quick note about me, I'm extremely new to PHP and programming, so I do not understand very much at the moment. My apologies if I'm missing something obvious, and thanks.

        it should replace your line:

        $comment = $_POST['comment'];

          Excellent, that did it! Thank you.

          I am wondering, is there any easy way to make it so that if someone enters a URL without http://www or even www before it to be linkable?

          I tested a comment using test.com but it wouldn't link, I had to type www.test.com or http://www.test.com for it to be linked.

          Thanks again for your help, appreciate it.

            That did it, absolutely fixed now. Many thanks, so glad you offered the help! Take care.

              5 days later

              A quick question to follow up - I noticed that if people post a link as follows:

              http://phpbuilder.com

              it looks like this script at http://www.m-bread.com/resources/urls2linksComplex does not automatically link URL's entered without the www after the http://

              Here is the code:

              
              function urls2linksComplex($text, $schemes = null, $tlds = 'normal'){
                //"urls2links - Complex" function by Martin Pain / m-bread ( http://m-bread.com/resources/php/functions/urls2linksComplex )
                //This function can be distributed under the Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License
                //( http://creativecommons.org/licenses/by-sa/2.0/uk/ )
                //Please leave these comments intact.
                if($schemes == 'normal'){
                  $scheme = '(?:[Hh][Tt]|[Ff])[Tt][Pp][Ss]?';
                }elseif( is_array($schemes) ){
                  $scheme = '(?:' . implode('|', $schemes) . ')';
                }elseif( is_string($schemes) ){
                  $scheme = $schemes;
                }else{
                  $scheme = '[a-zA-Z][a-zA-Z0-9\-+.]*';
                };//EoIF
                if($tlds == 'normal'){
                  $tldExclude = array('doc', 'xls', 'txt', 'rtf', 'jpeg', 'jpg', 'gif', 'png', 'exe', 'html', 'htm', 'zip', 'gz', 'scr', 'rar', 'php', 'php3', 'inc', 'ico', 'bmp', 'asp', 'jsp', 'dat', 'lnk', 'cab', 'csv', 'xml', 'xsl', 'xsd', 'svg', 'psp', 'psd', 'pdf', 'bak', 'wav', 'mp3', 'm4v', 'midi', 'wmv', 'wma', 'js', 'css', 'ppt', 'pps', 'mdb');
                }elseif( is_array($tlds) ){
                  $tldExclude = $tlds;
                }elseif( is_string($tlds) ){
                  $tldExclude = array($tlds);
                }else{
                  $tldExclude = array();
                };//EoIF
                  $userinfo = '(?:(?:[a-zA-Z0-9\-._~!$&\'()*+,;=:]|%[0-9A-Fa-f]{2})*@)?';
                    $decOctet = '(?:[0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
                   $ipv4 = '(?:'.$decOctet.'\.){3}'.$decOctet;
                   $regname = '(?:(?:[0-9A-Za-z][0-9A-Za-z\-]*[0-9A-Za-z]|[0-9A-Za-z])\.)+[a-zA-Z]{2,6}';
                  $host = '('.$ipv4.'|'.$regname.')';
                  $port = '(?::[0-9]*)?';
                 $authority = '((?://)?'.$userinfo.$host.$port.')';
                 $path = '(?:/(?:[a-zA-Z0-9\-._~!$&\'()*+,;=:]|%[0-9A-Fa-f]{2})*?)*';
                 $query = '(?:\?(?:[a-zA-Z0-9\-._~!$&\'()*+,;=:/?]|%[0-9A-Fa-f]{2})*?)?';
                 $fragment = '(?:#(?:[a-zA-Z0-9\-._~!$&\'()*+,;=:/?]|%[0-9A-Fa-f]{2})*?)?';
                $pattern = '\b(('.$scheme.'\:)?'.$authority.$path.$query.$fragment.')($|[^\w/][<\s]|[<\s]|[^\w/]$)';
                $replacement = '( !in_array( substr(\'$4\', strrpos(\'$4\', \'.\')+1), $tldExclude) )?\'<a href="\'.((\'$2\' == \'\')?((strpos(\'$3\', \'@\'))?\'mailto:$1\':\'http://$1\'):\'$1\').\'">$1</a>$5\':\'$0\'';
                return preg_replace('¦'.$pattern.'¦e', $replacement, $text);
              };//EoFn urls2links
              
              
              

              Wondering if anyone knows how to implement that? Thanks in advance for any consideration

                if you try the demo on his web page the links with out www are converted correctly,i wonder if its something your doing.

                  Write a Reply...