我有一個文本變數,其中包含具有相對或絕對路徑的多個影像。我需要檢查 src 屬性是否以開頭http或https忽略它,但如果它以開頭/或類似的內容開頭,abc/則在前面添加一個基本 url。
我試過如下:
<?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" />
任何人都可以幫助我糾正它。
uj5u.com熱心網友回復:
以下模式將查找src不以httpor開頭的屬性https。然后對于以正斜杠開頭的相對路徑,在將$base字串添加到src值之前將洗掉前導斜杠。
代碼:(演示)
$base = 'https://example.com/';
echo preg_replace('~ src="(?!http)\K/?~', $base, $html);
輸出:
<img src="https://example.com/docs/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" />
分解:
~ #starting pattern delimiter
src=" #match space, s, r, c, =, then "
(?!http) #only continue matching if not https or http
\K #forget any previously matched characters so they are not destroyed by the replacement string
/? #optionally match a forward slash
~ #ending pattern delimiter
至于你的模式,/<img src=\"[^http|https]([^\"]*)\"/:
[^http|https]實際上意味著“匹配不在此串列中的單個字符:|,h,t,p, ands。它可以簡化為[^|hpst]因為“否定字符類”中列出的字符的順序是不相關的,重復字符是沒有意義的。所以你看,[^...]不是您所說的“字串以某物或某物開頭”。- 捕獲子字串中的所有剩余字符直到下一個雙引號并意圖在替換中再次使用它是不必要的。這就是為什么我使用
\K來確定$base應該注入的位置而不是([^\"]*).
此外,在處理有效的 HTML 檔案時,我總是推薦 DOM 決議器的穩定性。您可以使用帶有 XPath 的 DOMDocument 來定位符合條件的元素并在src沒有正則運算式的情況下修改屬性。
代碼:(演示)
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//img[not(starts-with(@src, 'http'))]") as $node) {
$node->setAttribute('src', $base . ltrim($node->getAttribute('src'), '/'));
}
echo $dom->saveHTML();
相關答案:https : //stackoverflow.com/a/48837947/2943403
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395522.html
上一篇:在jquery中呼叫類方法
