我正在使用PHP中的preg_replace函数,并试图用 bit.ly 缩短的链接替换用户提交的url:
$comment = preg_replace( '/(http|ftp)+(s)?:(//)((w|.)+)(/)?(S+)?/i', '', $strText );
这将仅显示注释并"清除"URL。问题是我如何从文本中获取 URL 并在以后附加它?
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/2002n";
$text.= "Last christmas was 12/24/2001n";
// 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 的回调函数。它将接收匹配项作为参数,并在内部根据这些匹配项形成替换字符串。