Chris Chris - 3 months ago 12
jQuery Question

Modify a wildcard string within two other strings

Assuming I have the following code as the value of a variable (I can use either JS or PHP for this):

<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>


Is there a way I can convert the image filenames to lower case whilst preserving the case of everything else, and then rewrite all of the new code into the variable?

If the solution involves finding all instances of
src="*"
(or, anything between the strings
src="
and
"
) and converting them to lower case, that would be fine (I'm happy with the
src
values of any future elements I add being converted as well).

Answer

With PHP where $html is your html content:

$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();