【问题标题】:Replace exact domain with preg_replace用 preg_replace 替换确切的域
【发布时间】:2023-03-17 08:06:01
【问题描述】:

我有这个用于 preg_replace 的正则表达式。 他正在替换给定字符串中的所有网址。

现在我只需要替换 t.co 网址。 https://t.co/*等

preg_replace('/\b((https?|ftp|file):\/\/|www\.)[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', ' ', $text);

preg_replace 怎么做?

【问题讨论】:

标签: php regex


【解决方案1】:

您可以使用 preg_replace 并仅匹配特定的网址:

\bhttps?://t\.co/\S*

说明

  • \b字边界
  • https?:// 匹配可选 s 和 :// 的协议
  • t\.co匹配t.co
  • /\S* 匹配 / 和 0+ 个非空白字符

Regex demo

示例代码

preg_replace('~\bhttps?://t\.co/\S*~i', ' ', $text);

【讨论】:

    【解决方案2】:

    可能不是最有效的解决方案,但您可以试试preg_replace_callback()

    例如:

    preg_replace_callback('/\b((https?|ftp|file):\/\/|www\.)[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', function ($matches) {
        $url = $matches[0];
        if (preg_match('/^((https?:)?\/\/)?(www\.)?t\.co\b/i', $url)) {
            return ' ';
        } else {
            return $url;
        }
    }, $text);
    

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 2015-08-09
      • 1970-01-01
      • 2014-06-10
      相关资源
      最近更新 更多