2017-08-08 52 views
0

所以我现在有这...如何找到,使链路和缩短文本块URL文本与PHP

<?php 

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

echo $textblockwithformatedlinkstoecho; 
?> 

不过,我想也缩短可点击链接到长约15个字符...

示例输入文本

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

需要的输出文本

I recommend you visit example.com/fol... for more information. 
+1

您可以使用[preg_replace_callback()](http://php.net/manual/en/function.preg-replace-callback.php)在替换之前对其进行操作。 –

回答

0

您可以使用preg_replace_callback()来处理匹配。

例子:

$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а-яА-Я()[email protected]:%_+.~#?&;//=]+)!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; 

你可能需要修改,虽然您正则表达式,因为它不符合\ -characters您在网址的查询字符串有。

+0

非常感谢你,在示例链接中的字符来自我脸上种植键盘,所以应该与真正的URL工作正常。 – F3Speech