我正在使用php中的 preg_replace 函数,并尝试替换用户提交的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/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的回调函数。它将收到与参数的匹配项,并且您将在您的内部形成,具体取决于这些匹配项,替换字符串。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top