Hi All,
Having a bit of a nightmare getting this script to work as intended so wondered if anyone could shed some light on what's going on...
Basically, I have html stored in a variable $Template which contains text links and forms. I'm trying to search through that html and append a few variables onto the href and action attributes.
E.g. So
<a href="index.php">Text Link</a>
would become
<a href="index.php?this=that">Text Link</a>
And the same with the <form action="index.php"> attribute.
Here's what I've got:
$CS_VARS = 'this=that&';
$CS_VARS = substr($CS_VARS, 0, strlen($CS_VARS)-1);
if (isset($CS_VARS) && !empty($CS_VARS)) {
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
if(preg_match_all("/$regexp/siU", $Template, $regs, PREG_SET_ORDER)) {
foreach($regs as $reg) {
//href value
$link = $reg[2];
//If link contains a query
if (parse_url($link, PHP_URL_QUERY)) {
$mlink = $link.'&' . $CS_VARS;
} else {
$mlink = $link.'?' . $CS_VARS;
}
//Repalce in html
$Template = str_replace($link, $mlink, $Template);
}
}
$regexp2 = "<form\s[^>]*action=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/form>";
if(preg_match_all("/$regexp2/siU", $Template, $regs2, PREG_SET_ORDER)) {
foreach($regs2 as $reg2) {
//action value
$link2 = $reg2[2];
//If action contains a query
if (parse_url($link2, PHP_URL_QUERY)) {
$mlink2 = $link2.'&' . $CS_VARS;
} else {
$mlink2 = $link2.'?' . $CS_VARS;
}
//Repalce in html
$Template = str_replace($link2, $mlink2, $Template);
}
}
}
It seems to work, but when multiple forms are in the html, the $CS_VARS would repeat themselves so I actually end up with:
<form action="index.php?this=that&this=that&this=that... etc.
Also, for the text links it seems to sometimes remove the last character from the link before appending the $CS_VARS so I get:
<a href="index.php?id=123&this=that"> instead of
<a href="index.php?id=1234&this=that">
Any ideas as to what I'm doing wrong?
Cheers