cut long url

Discussion in 'PHP' started by wahyuagung, Aug 17, 2012.

  1. #1
    Hi, please help.


    $abc = get_settings('home') . strip_tags($item->get_title());
    
    echo $abc;
    Code (markup):
    The first line generates link from title, how do I display only 5 first words in the URL?
    ex: hxxp://www.domain.com/let-me-show-you-that-i-have-very-very-very-very-long-urls
    result: hxxp://www.domain.com/let-me-show-you-that

    Thanks for help :)
     
    Solved! View solution.
    wahyuagung, Aug 17, 2012 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,899
    Likes Received:
    4,555
    Best Answers:
    123
    Trophy Points:
    665
    #2
    There's bound to be a better way but I'd do something like this

    $abc = get_settings('home') . strip_tags($item->get_title());
    $bits = explode('/',$abc);
    $full = $bits[count($bits)-1];
    
    $words = explode('-',$full);
    $num = min(count($words), 4);
    
    $short = '';
    for ($i = 0; $i <= $num, $i++) {
       $short .= $words[$i];
    }
    
    $bits[count($bits)-1] = $short;
    
    $newlink = implode('/', $bits);
    
    PHP:
    I haven't tested that so it may have some errors but read through it, do some var_dumps where you aren't sure what is going on, check php.net and it should work.
     
    sarahk, Aug 17, 2012 IP
  3. #3
    If you want to reduce the length of the url, then my guess would be, you should reduce it according to its length and not by no. of words.

    for e.g. try something like:

    
    $abc = substr($abc, 0, 70);
    
    PHP:
    Which will limit the url to 70 characters.
     
    prabhunimish, Aug 18, 2012 IP
  4. BRUm

    BRUm Well-Known Member

    Messages:
    3,086
    Likes Received:
    61
    Best Answers:
    1
    Trophy Points:
    100
    #4
    That's it. Good answer.

    Wahyuagung, It looks like you're using a framework, if this is the case stop and learn PHP first. You shouldn't touch a framework if you don't know the underlying language..
     
    BRUm, Aug 18, 2012 IP