4

我在 PHP 中使用preg_replace函数,并试图用 bit.ly 缩短链接替换用户提交的 url:

$comment = preg_replace( '/(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/i', '', $strText );

这将仅显示评论并“清除”网址。问题是如何从文本中获取 URL 并在以后附加它?

4

1 回答 1

3

preg_replace_callback()

来自 php.net 的示例:

<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
  // as usual: $matches[0] is the complete match
  // $matches[1] the match for the first subpattern
  // enclosed in '(...)' and so on
  return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
            "|(\d{2}/\d{2}/)(\d{4})|",
            "next_year",
            $text);

?>

定义一个替换 URL 的回调函数。它将接收匹配项作为参数,并在您内部根据这些匹配项形成一个替换字符串。

于 2012-05-20T21:27:18.917 回答