【问题标题】:How can you get the replaced text with preg_replace?如何使用 preg_replace 获得替换的文本?
【发布时间】:2012-05-27 11:39:36
【问题描述】:

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

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

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

【问题讨论】:

    标签: php string preg-replace bit.ly


    【解决方案1】:

    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 的回调函数。它将接收匹配项作为参数,并根据这些匹配项在您内部形成一个替换字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      • 2011-12-23
      • 2011-02-19
      • 1970-01-01
      相关资源
      最近更新 更多