[英]Modify a wildcard string within two other strings
假設我將以下代碼作為變量的值(為此,我可以使用JS或PHP):
<div class="container">
<h1>The Page Title</h1>
<img src="MyImage.JPG" class="graphic" />
<p>Some body copy...</p>
<img class="graphic" src="misc/SecondImage.JPG" />
</div>
有什么辦法可以將圖像文件名轉換為小寫字母,同時保留其他所有字母的大小寫,然后將所有新代碼重寫為變量?
如果解決方案涉及查找src="*"
所有實例(或字符串src="
和"
之間的任何內容)並將其轉換為小寫字母,那將很好(我對任何將來元素的src
值都很滿意我還添加了轉換)。
使用PHP,其中$html
是您的html內容:
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$imgNodeList = $dom->getElementsByTagName('img');
foreach ($imgNodeList as $imgNode) {
$imgNode->setAttribute('src', strtolower($imgNode->getAttribute('src')));
}
echo $dom->saveHTML();
如果只需要在路徑庫(文件名)上使用小寫字母,則可以將DOM
與regex一起使用:
$html = <<< STR
<div class="container">
<h1>The Page Title</h1>
<img src="MyImage.JPG" class="graphic" />
<p>Some body copy...</p>
<img class="graphic" src="misc/SecondImage.JPG" />
</div>
STR;
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// Get all images
$images = $dom->getElementsByTagName('img');
foreach ($images as $img) {
$newSrc = preg_replace_callback('~[^/]+$~', function($match) {
// Convert file names to lowercase
return strtolower($match[0]);
}, $img->getAttribute('src'));
// Set new attribute value
$img->setAttribute('src', $newSrc);
}
// Save to original variable
$html = $dom->saveHTML();
echo $html;
輸出
<div class="container">
<h1>The Page Title</h1>
<img src="myimage.jpg" class="graphic">
<p>Some body copy...</p>
<img class="graphic" src="misc/secondimage.jpg">
</div>
試試下面的代碼
$('img').each(function(){ $(this).attr('src', $(this).attr('src').toLowerCase()) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="container"> <h1>The Page Title</h1> <img src="MyImage.JPG" class="graphic" /> <p>Some body copy...</p> <img class="graphic" src="misc/SecondImage.JPG" /> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.