Xhy*_*ynk 3 php url relative-path absolute-path str-replace
我已经看到了一些答案(比如这个),但我有一些更复杂的场景,我不确定如何解释。
我基本上有完整的 HTML 文档。我需要用绝对 URL替换每个相对 URL。
来自潜在 HTML 的元素如下所示,也可能是其他情况:
<img src="/relative/url/img.jpg" />
<form action="/">
<form action="/contact-us/">
<a href='/relative/url/'>Note the Single Quote</a>
<img src="//example.com/protocol-relative-img.jpg" />
Run Code Online (Sandbox Code Playgroud)
期望的输出是:
// "//example.com/" is ideal, but "http(s)://example.com/" are acceptable
<img src="//example.com/relative/url/img.jpg" />
<form action="//example.com/">
<form action="//example.com/contact-us/">
<a href='//example.com/relative/url/'>Note the Single Quote</a>
<img src="//example.com/protocol-relative-img.jpg" /> <!-- Unmodified -->
Run Code Online (Sandbox Code Playgroud)
我不想替换协议相对 URL,因为它们已经用作绝对 URL。我想出了一些有效的代码,但我想知道是否可以稍微清理一下,因为它非常重复。
但我必须考虑单引号和双引号的属性值src, href, 和action(我是否遗漏了任何可以具有相对 URL 的属性?)同时避免协议相对 URL。
这是我到目前为止所拥有的:
// Make URL replacement protocol relative to not break insecure/secure links
$url = str_replace( array( 'http://', 'https://' ), '//', $url );
// Temporarily Modify Protocol-Relative URLS
$str = str_replace( 'src="//', 'src="::TEMP_REPLACE::', $str );
$str = str_replace( "src='//", "src='::TEMP_REPLACE::", $str );
$str = str_replace( 'href="//', 'href="::TEMP_REPLACE::', $str );
$str = str_replace( "href='//", "href='::TEMP_REPLACE::", $str );
$str = str_replace( 'action="//', 'action="::TEMP_REPLACE::', $str );
$str = str_replace( "action='//", "action='::TEMP_REPLACE::", $str );
// Replace all other Relative URLS
$str = str_replace( 'src="/', 'src="'. $url .'/', $str );
$str = str_replace( "src='/", "src='". $url ."/", $str );
$str = str_replace( 'href="/', 'href="'. $url .'/', $str );
$str = str_replace( "href='/", "href='". $url ."/", $str );
$str = str_replace( 'action="/', 'action="'. $url .'/', $str );
$str = str_replace( "action='/", "action='". $url ."/", $str );
// Change Protocol Relative URLs back
$str = str_replace( 'src="::TEMP_REPLACE::', 'src="//', $str );
$str = str_replace( "src='::TEMP_REPLACE::", "src='//", $str );
$str = str_replace( 'href="::TEMP_REPLACE::', 'href="//', $str );
$str = str_replace( "href='::TEMP_REPLACE::", "href='//", $str );
$str = str_replace( 'action="::TEMP_REPLACE::', 'action="//', $str );
$str = str_replace( "action='::TEMP_REPLACE::", "action='//", $str );
Run Code Online (Sandbox Code Playgroud)
我的意思是,它有效,但它uuugly,我想可能有更好的方法来做到这一点。
我认为<base>元素就是你要找的...
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
该<base>是去在一个空元素<head>。Using<base href="https://example.com/path/" />将告诉文档中的所有相对 URL 来引用https://example.com/path/而不是父 URL
新答案
如果您的真实 html 文档是有效的(并且有父/包含标签),那么最合适和可靠的技术将是使用适当的 DOM 解析器。
以下是如何使用 DOMDocument 和 Xpath 优雅地定位和替换您指定的标签属性:
Code1 - 嵌套 Xpath 查询:(演示)
$domain = '//example.com';
$tagsAndAttributes = [
'img' => 'src',
'form' => 'action',
'a' => 'href'
];
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($tagsAndAttributes as $tag => $attr) {
foreach ($xpath->query("//{$tag}[not(starts-with(@{$attr}, '//'))]") as $node) {
$node->setAttribute($attr, $domain . $node->getAttribute($attr));
}
}
echo $dom->saveHTML();
Run Code Online (Sandbox Code Playgroud)
Code2 - 带条件块的单个 Xpath 查询:(演示)
$domain = '//example.com';
$targets = [
"//img[not(starts-with(@src, '//'))]",
"//form[not(starts-with(@action, '//'))]",
"//a[not(starts-with(@href, '//'))]"
];
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query(implode('|', $targets)) as $node) {
if ($src = $node->getAttribute('src')) {
$node->setAttribute('src', $domain . $src);
} elseif ($action = $node->getAttribute('action')) {
$node->setAttribute('action', $domain . $action);
} else {
$node->setAttribute('href', $domain . $node->getAttribute('href'));
}
}
echo $dom->saveHTML();
Run Code Online (Sandbox Code Playgroud)
旧答案:(...正则表达式不是“DOM-aware”并且容易受到意外破坏)
如果我正确理解你,你心里就有一个基本值,你只想把它应用到相对路径上。
代码:(演示)
$html=<<<HTML
<img src="/relative/url/img.jpg" />
<form action="/">
<a href='/relative/url/'>Note the Single Quote</a>
<img src="//site.com/protocol-relative-img.jpg" />
HTML;
$base='https://example.com';
echo preg_replace('~(?:src|action|href)=[\'"]\K/(?!/)[^\'"]*~',"$base$0",$html);
Run Code Online (Sandbox Code Playgroud)
输出:
<img src="https://example.com/relative/url/img.jpg" />
<form action="https://example.com/">
<a href='https://example.com/relative/url/'>Note the Single Quote</a>
<img src="//site.com/protocol-relative-img.jpg" />
Run Code Online (Sandbox Code Playgroud)
模式分解:
~ #Pattern delimiter
(?:src|action|href) #Match: src or action or href
= #Match equal sign
[\'"] #Match single or double quote
\K #Restart fullstring match (discard previously matched characters
/ #Match slash
(?!/) #Negative lookahead (zero-length assertion): must not be a slash immediately after first matched slash
[^\'"]* #Match zero or more non-single/double quote characters
~ #Pattern delimiter
Run Code Online (Sandbox Code Playgroud)