【问题标题】:How to replace http for https in string but only on specific domains in PHP如何在字符串中将 http 替换为 https,但仅限于 PHP 中的特定域
【发布时间】:2016-07-11 12:36:50
【问题描述】:

我需要解析 html 内容的字符串,并在可能的情况下用 https 替换其他域上的图像的 url,无论它们是 http。问题是并非所有外部域都支持 https,因此我无法将 http 替换为 https。

所以我想使用我知道使用 https 的域列表来执行此操作。

还有一点额外的复杂性,即搜索必须适用于与 www 无关的域。是否添加。

使用@Wiktor 给出的示例,我有一些接近我想要的东西,但这需要在找到匹配项时反转运行替换,而不是在找不到匹配项时,因为此代码当前起作用。

/http(?!:\/\/(?:[^\/]+\.)?(?:example\.com|main\.com)\b)/i

【问题讨论】:

  • 询问正则表达式,没有样本输入,没有想要的输出。有什么不对劲...
  • 不要为此使用正则表达式。您有太多要求期望正则表达式能够正确处理此问题。
  • 我正在喂我的女儿,让我吃完。也许$re = '/http(?=:\/\/(?:[^\/]+\.)?(?:' . implode("|", array_map(function ($x) {return preg_quote($x); }, $domains)) . ')\b)/i'; echo preg_replace($re, "https", $s);

标签: regex replace preg-replace


【解决方案1】:

相信你可以使用

$domains = array("example.com", "main.com");
$s = "http://example.com http://main.main.com http://let.com";
$re = '/http(?=:\/\/(?:[^\/]+\.)?(?:' 
      . implode("|", array_map(function ($x) {
             return preg_quote($x); 
          }, $domains)) 
      . ')\b)/i'; 
echo preg_replace($re, "https", $s);
// => https://example.com https://main.main.com http://let.com

IDEONE demo

正则表达式匹配:

  • http - http 仅在后跟...
  • (?= - 积极前瞻的开始
    • :\/\/ - :// 文字子字符串
    • (?:[^\/]+\.)? - 除了/. 之外的1+ 个字符的可选序列
    • (?: + implode 代码 - 创建一个替代组来转义单个文字分支(以匹配任何一个替代项,examplemain 等)
    • ) - 轮换组结束
  • \b - 字边界
  • ) - 前瞻结束
  • /i - 不区分大小写的修饰符。

【讨论】:

  • 感谢@WiktorStribiżew!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-05
  • 2021-07-04
  • 2021-07-27
相关资源
最近更新 更多