我在很多论坛上都看到他们从中心剪下网址并加上3个点,如果它很长就是为了缩短它。
示例:ajaxify multipart encoded form (upload forms) ---将是---> http://stackoverflow.c...ed-form-upload-forms
如何使用纯PHP?
谢谢
答案 0 :(得分:10)
e.g。通过preg_replace()
$testdata = array(
'http://stackoverflow.com/questions/1899537/ab',
'http://stackoverflow.com/questions/1899537/abc',
'http://stackoverflow.com/questions/1899537/abcd',
'http://stackoverflow.com/questions/1899537/ajaxify-multipart-encoded-form-upload-forms'
);
foreach ($testdata as $in ) {
$out = preg_replace('/(?<=^.{22}).{4,}(?=.{20}$)/', '...', $in);
echo $out, "\n";
}
打印
http://stackoverflow.com/questions/1899537/ab
http://stackoverflow.c...uestions/1899537/abc
http://stackoverflow.c...estions/1899537/abcd
http://stackoverflow.c...ed-form-upload-forms
答案 1 :(得分:3)
$url = "http://stackoverflow.com/questions/1899537/";
if(strlen($url) > 20)
{
$cut_url = substr($url, 0, 6);
$cut_url .= "...";
$cut_url .= substr($url, -6);
}
<a href="<?=$url; ?>"><?=$cut_url;?></a>
答案 2 :(得分:3)
@null 提供了一个很好的解决方案。但要注意UTF-8:http://de.wikipedia.org/wiki/Märchen如果>ä<失去一个重要的字节,可能会导致输出无效。
这是一个略微改进的版本,使用mb_string functions:
function short_url($url, $max_length=20)
{
mb_internal_encoding("UTF-8");
$real_length = mb_strlen($url);
if ( $real_length <= $max_length )
{
return $url;
}
$keep = round( $max_length / 2 ) - 1;
return mb_substr($url, 0, $keep) . '…' . mb_substr($url, -$keep);
}
// Test
print short_url('http://de.wikipedia.org/wiki/Märchen', 13);
// http:/…ärchen - not nice, but still valid UTF-8. :)