#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    3
    Rep Power
    0

    Manipulate the text-part of a link


    Hallo Forum,

    in a PHP-Project I manipulate a simple link with:

    PHP Code:
    function replace_sulr($str) { 
    $pattern '#(^|[^\"=]{1})(http://|ftp://|mailto:|news:)([^\s<>]+)([\s\n<>]|$)#sm'
    return 
    preg_replace($pattern,"\\1<a href=\"\\2\\3\" target=\"_blank\" class=\"crmnewsdetail_link\"><span class=\"crmnewsdetail_linkq\">&nbsp;</span>\\3</a>\\4",$str);
     } 
    ... and ist working.
    But Part 3 is sometimes too long. I would like to shorten the "linkname" if it is longer than 50 letters. And I would like to shorten it from the middle:

    wxw/en/snowboarding/episodes/1331581260962/chamaleon-the-project-begins
    should become to:
    xwx/en/sn...hamaleon-the-project-begins

    (wxw for w..w because of the rules)

    Is it possible to integrate this to a regex-pattern like this I'm using until now.

    Thanks for your help!
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,993
    Rep Power
    9397
    Use preg_replace_callback() and make the callback function shorten $3 before returning the new string. Like
    PHP Code:
    function replace_sulr($str) {
        
    $pattern '#(^|[^\"=]{1})(http://|ftp://|mailto:|news:)([^\s<>]+)([\s\n<>]|$)#sm';
        return 
    preg_replace_callback($pattern, function($match) {
            
    $format "%s<a href=\"%s%s\" target=\"_blank\" class=\"crmnewsdetail_link\"><span class=\"crmnewdetail_linq\">&nbsp;</span>%s</a>%s";
            list(, 
    $before$protocol$url$after) = $match;
            if (
    strlen($url) > 50) {
                
    $shorturl substr($url010) . "..." substr($url, -20);
            } else {
                
    $shorturl $url;
            }
            return 
    sprintf($format$before$protocol$url$shorturl$after);
        }, 
    $str);

  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    3
    Rep Power
    0
    Thanks ... but first I must work me throught this stuff ;-)
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    3
    Rep Power
    0

    Perfect ... Thanks


    I didn't know about preg_replace_callback. Never used bevor.
    Nice idea! And thanks again!

IMN logo majestic logo threadwatch logo seochat tools logo