Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Shorten URL by cutting it from the center?

Tags:

php

i've seen in many forums that they cut the url from the center and add 3 dots if it's long in order to shorten it.

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

How to do that using pure php?

Thank you

like image 633
CodeOverload Avatar asked Dec 06 '22 03:12

CodeOverload


2 Answers

e.g. 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
like image 142
VolkerK Avatar answered Dec 18 '22 22:12

VolkerK


You can use the substr function along 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>
like image 42
null Avatar answered Dec 19 '22 00:12

null