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 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟