PHP: Shorten the URL by cutting it off the center?

I saw in many forums that they cut out the URL from the center and added 3 dots if it is long to shorten it.

Example: ajaxify multipart encoded form (upload forms) --- Will ---> http: //stackoverflow.c...ed-form-upload-forms

How to do this using pure php?

thank

+3
source share
3 answers

eg. via 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";
}

prints

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
+7
source

You can use substr function with strlen

$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>
+3
source

@null . UTF-8: http://de.wikipedia.org/wiki/MΓ€rchen , > Γ€ < .

, mb_string:

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. :)
+3

Source: https://habr.com/ru/post/1740202/


All Articles