1

I have a function to append a query string to every <a> tag found in a HTML file. In that file I have some <a> tags commented which I need to target as well.

HTML

<!-- Commented link
    <a class="legal_link" target="_blank" href="https://commented-url.com">some text</a>
-->

<a href="https://url.com" target="_blank" class="btn_center">
    Some text
</a>

<!--[if mso]>
<v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="https://another-commented-url.com" target="_blank" style="height:55px;v-text-anchor:middle;width:300px;" arcsize="10%" stroke="f" fillcolor="#f7e7e7">
<w:anchorlock/>
<center>
<![endif]-->
    <a href="https://url.com" target="_blank" class="btn_center">
        Some text
    </a>
<!--[if mso]>
</center>
</v:roundrect>
<![endif]-->

PHP function

//Append query string to every a element
//-------------------------------------------------------------------------------------------------------------------------//
function appendQueryString($htmlContent, $queryString){
    $dom = new DOMDocument();
    $dom->loadHTML($htmlContent, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    $htmlElements = $dom->getElementsByTagName('a'); // Not getting commented tags


    foreach($htmlElements as $htmlElement){
        $htmlElementUrl = $htmlElement->getAttribute('href');
        $htmlElementUrlParsed = parse_url($htmlElementUrl);
        if($htmlElementUrlParsed['path'] == null){ $htmlElementUrl .= '/'; }
        $htmlElementUrlSeparator = ($htmlElementUrlParsed['query'] == NULL) ? '?' : '&';
        $htmlElementUrl = $htmlElementUrl . $htmlElementUrlSeparator . $queryString;
        $htmlElement->setAttribute('href', $htmlElementUrl);
    }

    return $dom->saveHTML();
}
maeq
  • 1,073
  • 1
  • 12
  • 23

0 Answers0