10/10/2018, 11:01
Giúp đỡ hàm tìm kiếm và thay thế - preg_replace
Chào các bạn.
Mình có 1 đoạn văn bản thế này
mình muốn url http://google.com.vn => <a href="http://google.com.vn">http://google.com.vn</a>
và http://bing.com cũng như thế.
Cách mình làm
Kết quả là
cái src ảnh cũng thành link luôn.
Mình không biết phải giải quyết thế nào mong các bạn giúp đỡ. Xin chân thành cảm ơn.
Mình có 1 đoạn văn bản thế này
Code:
<img src="http://example.com/logo.png" /> ra mat may chu moi http://google.com.vn giao trinh http://bing.com ket thuc
và http://bing.com cũng như thế.
Cách mình làm
Code:
preg_replace("/(http://[a-zA-Z-0-9._?/s]+)/", "<a href="$1" rel="nofollow">$1</a>", $content);
Code:
<img src="<a href="http://example.com/logo.png">http://example.com/logo.png</a>" /> ra mat may chu moi <a href="http://google.com.vn">http://google.com.vn</a> giao trinh <a href="http://bing.com">http://bing.com</a> ket thuc
Mình không biết phải giải quyết thế nào mong các bạn giúp đỡ. Xin chân thành cảm ơn.
Bài liên quan
function urlfix($url){
$in=array(
'# ((?:http?|ftp?|https)://(.*?)) #si',
);
$out=array(
' <a href="$1" rel="nofollow">$1</a> ',
);
return preg_replace($in,$out,$url);
}
Nhưng một số content thì đằng sau link là html tag nên nếu quy định space thì cũng không ổn bạn ah.
Mình nghĩ loại trừ link .jpg hay .png ra nhưng mình không biết viết thế nào cả. Ai biết chỉ giáo với.
chân thành cảm ơn.
Ai biết xin chỉ giáo
Cảm ơn nhiều.
/**
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$n ame$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/200...ment-spam.html
$nofollow = ( $other['nofollow'] ? ' rel="nofollow"' : null );
}
$value = "<a href=\"$key\"$target$nofollow>$key</a>";
}
?>
Cảm ơn rất nhiều.