开发者

PHP preg_replace shortening a string

开发者 https://www.devze.com 2023-02-06 16:07 出处:网络
So I\'ve got this php code: $text = preg_replace(\"/(\\s)http:\\/\\/([\\S]+?)(\\s)/i\" , \"$1[url=\\\"http://$2\\\"]http://$2[/url]$3\" , \" $text \");

So I've got this php code:

$text = preg_replace("/(\s)http:\/\/([\S]+?)(\s)/i" , 
"$1[url=\"http://$2\"]http://$2[/url]$3" , " $text ");

I guess it's replacing http://xyz.xyz.xyz kind of strings into [url=http://xyz.xyz.xyz]http://xyz.xyz.xyz[/url] 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 [url=http://xyz.xyz.xyz] http://xyz.xyz.xyz <-- this string [/url] 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 s开发者_如何学JAVAo 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消