douhunkuang8955 2017-08-08 15:03
浏览 23
已采纳

如何使用PHP在文本块中查找,链接和缩短URL文本

So I currently have this...

<?php

$textblockwithformatedlinkstoecho = preg_replace('!(((f|ht)tp(s)?://)[-a-zA-
Zа-яА-Я()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1" target="popup">$1</a>', 
$origtextwithlinks);

echo $textblockwithformatedlinkstoecho;
?>

But, I would like to also shorten the clickable link to around 15 chars in length...

Example input text

I recommend you visit http://www.example.com/folder1/folder2/page3.html?
longtext=ugsdfhsglshghsdghlsg8ysd87t8sdts8dtsdtygs9ysd908yfsd0fyu for more 
information.

Required output text

I recommend you visit example.com/fol... for more information.
  • 写回答

1条回答 默认 最新

  • dsaf415212 2017-08-08 15:22
    关注

    You can use preg_replace_callback() to manipulate the matches.

    Example:

    $text = "I recommend you visit http://www.example.com/folder1/folder2/page3.html?longtext=ugsdfhsglshghsdghlsg8ys\d87t8sdts8\dtsdtygs9ysd908yfsd0fyu for more information.";
    
    $fixed = preg_replace_callback(
        '!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9@:%_+.~#?&;//=]+)!i', 
        function($matches) {
            // Get the fully matched url
            $url  = $matches[0];
    
            // Do some magic for the link text, like only show the first 15 characters
            $text = strlen($url) > 15
                ? substr($url, 0, 15) . '...'
                : $url;
    
            // Return the new html link
            return '<a href="' . $url . '" target="popup">' . $text . '</a>';
        }, 
        $text
    );
    
    echo $fixed;
    

    You probably need to modify your regex though, since it doesn't match the \-characters you have in the query string in the url.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求