[英]PHP Regex Replace Image SRC Attribute
我正在嘗試找到一個正則表達式,它可以讓我替換圖像中的SRC
屬性。 這是我所擁有的:
function getURL($matches) {
global $rootURL;
return $rootURL . "?type=image&URL=" . base64_encode($matches['1']);
}
$contents = preg_replace_callback("/<img[^>]*src *= *[\"']?([^\"']*)/i", getURL, $contents);
在大多數情況下,這工作得很好,除了當 $contents 回顯到屏幕時消除src="
屬性之前的所有內容。最后, SRC
被正確更新,並且更新后的圖像 URL 之后的所有屬性都返回到屏幕。
我對使用 DOM 或 XML 解析庫不感興趣,因為這是一個如此小的應用程序。
如何修復正則表達式以便僅更新SRC
的值?
感謝您的時間!
使用懶惰的明星而不是貪婪的明星。
這可能是你的問題:
/<img[^>]*src *= *[\"']?([^\"']*)/
^
將其更改為:
/<img[^>]*?src *= *[\"']?([^\"']*)/
這樣, [^>]*
匹配括號表達式的最小可能數量,而不是最大可能。
做另一個分組並將其添加到返回值?
function getURL($matches) {
global $rootURL;
return $matches[1] . $rootURL . "?type=image&URL=" . base64_encode($matches['2']);
}
$contents = preg_replace_callback("/(<img[^>]*src *= *[\"']?)([^\"']*)/i", getURL, $contents);
我對使用 DOM 或 XML 解析庫不感興趣,因為這是一個如此小的應用程序。
不過,無論您的應用程序大小如何,這都是正確的方法。
請記住,當您使用 DOMDocument 修改元素時,您應該反向迭代以避免意外的異常情況 - 特別是在您刪除任何內容時。
這是一個使用 DOMDocument 的工作示例。 它比正則表達式更復雜,但並不是非常困難,並且對於可能需要的任何其他調整都更加靈活和健壯。
function inner_html($node) {
$innerHTML = "";
foreach ($node->childNodes as $child) {
$innerHTML .= $node->ownerDocument->saveHTML($child);
}
return $innerHTML;
}
function replace_src($html) {
$rootURL = 'https://example.com';
$dom = new DOMDocument();
if (mb_detect_encoding($html, 'UTF-8', true) == 'UTF-8') {
$html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
}
$dom->loadHTML('<body>' . $html . '</body>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
for ($els = $dom->getElementsByTagname('img'), $i = $els->length - 1; $i >= 0; $i--) {
$src = $els->item($i)->getAttribute('src');
$els->item($i)->setAttribute('src', $rootURL . '?type=image&URL=' . $src);
}
return inner_html($dom->documentElement);
}
$html = '
<div>
<img src="test123">
<img src="test456">
</div>
';
echo replace_src($html);
輸出:
<div>
<img src="https://example.com?type=image&URL=test123">
<img src="https://example.com?type=image&URL=test456">
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.