【发布时间】:2022-01-26 20:55:49
【问题描述】:
我有一个文本变量,其中包含多个具有相对或绝对路径的图像。我需要检查 src 属性是否以http 或https 开头,然后忽略它,但如果它以/ 或类似abc/ 开头,则添加一个基本网址。
我尝试如下:
<?php
$html = <<<HTML
<img src="docs/relative/url/img.jpg" />
<img src="/docs/relative/url/img.jpg" />
<img src="https://docs/relative/url/img.jpg" />
<img src="http://docs/relative/url/img.jpg" />
HTML;
$base = 'https://example.com/';
$pattern = "/<img src=\"[^http|https]([^\"]*)\"/";
$replace = "<img src=\"" . $base . "\${1}\"";
echo $text = preg_replace($pattern, $replace, $html);
我的输出是:
<img src="https://example.com/ocs/relative/url/img.jpg" />
<img src="https://example.com/docs/relative/url/img.jpg" />
<img src="https://docs/relative/url/img.jpg" />
<img src="http://docs/relative/url/img.jpg" />
这里的问题:我得到了 99% 的结果正确,但是当 src 属性以 docs/ 之类的东西开头时,它的第一个字母被切断了。 (请检查输出中的第一个 img src)
我需要的输出是:
<img src="https://example.com/docs/relative/url/img.jpg" /><!--check this and compare with current result, you will get the difference -->
<img src="https://example.com/docs/relative/url/img.jpg" />
<img src="https://docs/relative/url/img.jpg" />
<img src="http://docs/relative/url/img.jpg" />
谁能帮我纠正一下。
【问题讨论】: