John Davidson

php - Changing the href of a link in a mustache template with DOMDocument

0 comments
Message:


I am facing a problem, when I try to change the href of a link in a mustache template using DOMDocument.


Consider the following code:


$template = "<a href='{{url}}'>Link</a>";

$document = new DOMDocument();
$document->loadHTML($template, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOXMLDECL);

foreach ($document->getElementsByTagName('a') as $link) $link->setAttribute('href', 'https://myurl.com?redirect=' . $link->getAttribute('href'));

$template = $document->saveHTML();
echo $template; // <a href='https://myurl.com?redirect=%7B%7Burl%7D%7D'>Link</a>

If later I try to render this via mustache, I won't be able ofc because the {{}} part was encoded. Is there any way to tell DOMDocument to stop auto validating my href attributes? Or is there any alternative with which I can easily get a html string, find all <a></a> elements in it, and change their href attribute?


EDIT: Obviously this is a simple example, and in my real life scenario it is not a possibility for me, to prerender the HTML with mustache, and replace the links then.



My Answer:
One possible solution is to use a regular expression to find and replace the href attribute in the HTML string before loading it into the DOMDocument. Here's an example:

php
$template = "Link";

// Replace the {{url}} placeholder with the actual URL
$template = str_replace("{{url}}", "https://example.com", $template);

// Use a regular expression to find and replace the href attribute
$template = preg_replace("/]*\s+)?href=('|\"){{(.*?)}}('|\")/", " // Do any additional processing if needed
}

$template = $document->saveHTML();
echo $template;


This way, you can manipulate the href attribute before it gets encoded by the DOMDocument. Just make sure to adjust the regular expression pattern to match your specific needs.

Rate this post

3 of 5 based on 1156 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us