将协议相对url替换为http://.


Replace protocol relative URLs with http://

我有一个应用程序,加载本地文件和附加下载的HTML数据。这些数据有时包含协议相对url,基本上是//domain.com/file而不是http://domain.com/file。好处是,这将自动选择适当的协议,这将是很好的web域,但不是当本地加载-它然后使用file:// -协议。

因此,我需要用attr="http://domain.com/file"替换attr="//domain.com/file"的所有出现-实质上是在前面添加http:。我想最简单的是在PHP中实现,我该如何实现呢?

使用preg_replace,如果'attr'仅在标签内:

$content = preg_replace('@(<.+?)(attr="//)(.*?>)@', '''1attr="http://''3', $content);

假设 attr="//文本不会像<p> ... attr="// ... </p>那样显示为自由文本

使用str_replace

$contents = str_replace('attr="//', 'attr="http://', $contents);

使用preg_replace

$contents = preg_replace('|attr="//|', 'attr="http://', $contents);