检测从SQL数据链路和只显示50个字母的它作为文本

问题描述 投票:1回答:1

我一直在努力优惠券代码的网站,并能修改某些设置,但是这一次似乎是困扰着我......

 <?php $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    $text = $item->description;               
    if(preg_match($reg_exUrl, $text, $url)) {
        $linktext = substr($url[0], 0, 50);
        $text1 = preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow"><b>'.$linktext.'...</b></a>', $text);
    } 
    else 
    {
        $text1= $text;
    }
    $modeddescription = $text ; //string retrieved from SQL ?> 
<?php echo ( !empty( $item->description ) ? '<span>' . nl2br($text1) . '</span>' : t( 'theme_no_description', 'No description.' ) ); ?>

上面的代码输出从SQL优惠券代码的描述,它应该检测从SQL文本数据链路。它所做的是它只能检测到第一个链接,如果在该文本10个链接,所有的节目10个链接将是相同的......例如,如果文本是像

http://google.com and http://facebook.com are big companies.
a good example for shopping site is http://amazon.com

它会输出

http://google.com and http://google.com are big companies.
a good example for shopping site is http://google.com

我希望有人能帮助我解决这个问题。我可以使用另一种代码,并单独检测所有链接,但我真的不希望显示在页面中的500个字符长的链接。只是想显示免得作为链接标题的第一个字母50。

这个代码能够检测所有的个人联系,但如何将它添加行间距和50个字符的限制?

$string = preg_replace( "~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~","<a href=\"\\0\">\\0</a>", $text);
echo ".$string.";?>
php url preg-replace preg-match
1个回答
0
投票

preg_replace_callback()是这个职位的合适的工具。这可以让你做一个preg_呼叫,然后有条件地修改重置价值。

编号:(Demo

$pattern = "~(?:f|ht)tps?://[a-z\d.-]+\.[a-z]{2,3}\S*~i";

$text = 'http://google.com
and http://facebook.com?12345678901234567890123456789012345678901234567890 are big companies.
A good example for shopping site is http://amazon.com';

echo preg_replace_callback($pattern, function($m) {
    return "<a href=\"{$m[0]}\" rel=\"nofollow\"><b>" . (strlen($m[0]) > 50 ? substr($m[0], 0, 50) . "..." : $m[0]) . "</b></a>";
}, $text);

输出:

<a href="http://google.com" rel="nofollow"><b>http://google.com</b></a>
and <a href="http://facebook.com?12345678901234567890123456789012345678901234567890" rel="nofollow"><b>http://facebook.com?123456789012345678901234567890...</b></a> are big companies.
A good example for shopping site is <a href="http://amazon.com" rel="nofollow"><b>http://amazon.com</b></a>
© www.soinside.com 2019 - 2024. All rights reserved.