如何使用preg_replace获取替换的文本?

时间:2012-05-20 21:23:43

标签: php string preg-replace bit.ly

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

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

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

1 个答案:

答案 0 :(得分: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的回调函数。它将接收匹配作为参数,在内部,您将根据这些匹配形成替换字符串。