PDA

View Full Version : تشخیص لینک در مطلب



tecnocomputer2
یک شنبه 06 تیر 1389, 21:25 عصر
سلام یه متغیر داریم که توش این نوشته شده:



$str = "salam, halet khobe?
in site mane: http://site.com
khoshhal misham biyay
bye"


میخام وقتی مقدار منتغیرم چاپ شه اونجاهایی که لینک داره خودکار لینک نشون بده، یعنی:



$str = "salam, halet khobe?
in site mane: <a href="http://site.com">http://site.com</a>
khoshhal misham biyay
bye"


یه کد نوشتم که از طریق همون کلمه http تشخیص میده کار هم میکنه، فکر کنم بهتر از کد من هم هست. دوستان اگه کدی چیزی دارن بزارن (هر کدی) ممنونم

pashaie
یک شنبه 06 تیر 1389, 22:29 عصر
یه کد نوشتم که از طریق همون کلمه http تشخیص میده کار هم میکنه، فکر کنم
بهتر از کد من هم هست. دوستان اگه کدی چیزی دارن بزارن (هر کدی) ممنونم




<?php
/**
NAME : autolink()
VERSION : 1.0
AUTHOR : J de Silva
DESCRIPTION : returns VOID; handles converting
URLs into clickable links off a string.
TYPE : functions
======================================*/

function autolink( &$text, $target='_blank', $nofollow=true )
{
// grab anything that looks like a URL...
$urls = _autolink_find_URLS( $text );
if( !empty($urls) ) // i.e. there were some URLS found in the text
{
array_walk( $urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow) );
$text = strtr( $text, $urls );
}
}

function _autolink_find_URLS( $text )
{
// build the patterns
$scheme = '(http:\/\/|https:\/\/)';
$www = 'www\.';
$ip = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
$subdomain = '[-a-z0-9_]+\.';
$name = '[a-z][-a-z0-9]+\.';
$tld = '[a-z]+(\.[a-z]{2,2})?';
$the_rest = '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}';
$pattern = "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$na me$tld))$the_rest";

$pattern = '/'.$pattern.'/is';
$c = preg_match_all( $pattern, $text, $m );
unset( $text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern );
if( $c )
{
return( array_flip($m[0]) );
}
return( array() );
}

function _autolink_create_html_tags( &$value, $key, $other=null )
{
$target = $nofollow = null;
if( is_array($other) )
{
$target = ( $other['target'] ? " target=\"$other[target]\"" : null );
// see: http://www.google.com/googleblog/2005/01/preventing-comment-spam.html
$nofollow = ( $other['nofollow'] ? ' rel="nofollow"' : null );
}
$value = "<a href=\"$key\"$target$nofollow>$key</a>";
}


کد نمونه:




<?php
// let's say we have a dummy string read from a file or db
$text = 'For more information, visit our website http://www.desilva.biz or
www.gidforums.com/ to discuss this. This topic is discussed here:
http://www.gidforums.com/t-1787.html';


// first we pass it through htmlentities()
$text = htmlentities( $text );


// include the 3 functions above
include_once( 'includes/the_3_functions_above_are_in_this_file.php' );
// NOW we run it through autolink()!
autolink( $text );
// display the text in a web page
echo $text."<br />\r\n";
?>

منبع » http://www.gidforums.com/t-1816.html