加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 16:45:26 所属栏目:PHP教程 来源:网络整理
导读:我在 PHP中使用preg_replace函数,并尝试用bit.ly缩短的链接替换用户提交的url: $comment = preg_replace( '/(http|ftp)+(s)?:(//)((w|.)+)(/)?(S+)?/i','',$strText ); 这将仅显示评论并“清除”网址.问题是如何从文本中获取URL并在以后添加? 解决方
我在 PHP中使用preg_replace函数,并尝试用bit.ly缩短的链接替换用户提交的url:

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

这将仅显示评论并“清除”网址.问题是如何从文本中获取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的回调函数.它会将匹配作为参数接收,在内部,您将根据这些匹配形成替换字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读