I am working on a php script for a custom cms that will replace a custom tag with information from a database.
There would be a tag like below
<!-- NAV id="123" suffix="somethinghere" prefix="somethingelse" -->
I need to pull out the id, suffix, and prefix attributes. The code below works great if there is only one instance of this tag on the page, but if I have more than one, or if "-->" is anywhere else on the page it does not work properly. It matches everything between the first
"<!--"
and the last
"-->"
instead of returning each match separately.
Here is my current code. If it were working properly it would replace the entire tag with the value of "id", eventually that will be data from the database.
<?php
global $lastNav, $html;
//the html content
$html = '<html><body><hr><br>Hi this is my content<br> <!-- NAV id="123" suffix="<br />" prefix="•" --> <br>Some more content here <!-- NAV id="125" suffix="<br />" prefix="•" --> </body></html>';
$regexNavPattern = '<!-- NAV.*?(?:(?:\s+(id)="([^"]+)")|(?:\s+(prefix)="([^"]+)")|(?:\s+(suffix)="([^"]+)")|(?:\s+[^\s]+))+.*-->';
preg_replace_callback($regexNavPattern, "parseNav", $html);
function parseNav($navData) {
global $lastNav, $html;
foreach($navData as $key=>$value) {
if($key == 0) { $lastNav['replace'] = '<'.$value.'>'; }
if($value == 'id') { $lastNav['id'] = $navData[$key+1]; }
if($value == 'prefix') { $lastNav['prefix'] = $navData[$key+1]; }
if($value == 'suffix') { $lastNav['suffix'] = $navData[$key+1]; }
}
$html = str_replace($lastNav['replace'], $lastNav['id'], $html);
}
echo $html;
?>
At this point I am not concerned about case sensitivity. There is a chance that the attributes may contain special characters including single or double quotes.
Hopefully I explained this well enough. Thanks in advance.