问题描述:

So I've got this php code:

$text = preg_replace("/(\s)http:\/\/([\S]+?)(\s)/i" ,

"$1http://$2$3" , " $text ");

I guess it's replacing http://xyz.xyz.xyz kind of strings into http://xyz.xyz.xyz inside of a given text (in my case it's a postparser for my forum) right?

now what I'm trying to do is, to limit the stringlength of the http://xyz.xyz.xyz-string that comes inside the http://xyz.xyz.xyz <-- this string

because sometimes users post very long links and those are messing up my forum design and look very ugly anyway.

is there a way I could realize that in php, while keeping the 1. http link like it is so it still links correct?

big thanks in advance! :)

网友答案:

How about:

$text = preg_replace("/(\s)http:\/\/([\S]{,40})([\S]*?)(\s)/i",
"$1[url=\"http://$2$3\"]http://$2[/url]$4" , " $text ");

to limit it to a 40 character URL?

网友答案:

You could maybe just split the process in a couple of lines of code instead of one do-it-all preg_replace.

  1. preg_match
  2. check strlen for match
  3. shorten url between [url][/url] if need
  4. build replacement string
  5. str_replace match with replacement string
网友答案:

Use preg_replace_callback so that you have more control over the replacement. (e.g. use $2 in [url=...] and use a shorten version of $2 in the text.

function replace_links($matches) {

    $url = $matches[2];
    $short_url = preg_replace('~^([^/]*)/(.{14})(.{3,})(.{18})$~', '$1/$2...$4', $url);

    return $matches[1] . '[url="http://' . $url . '"]http://' . $short_url . '[/url]' . $matches[3];

}

$text = preg_replace_callback("/(\s)http:\/\/([\S]+?)(\s)/i", 'replace_links', " $text ");

(Codepad)

You can see that I use another preg_replace for transforming a very long URL to a short one. I cut it in the middle, while fully preserving the domain name, but you may use any cutting pattern you want.

相关阅读:
Top