I am building a script that will process a URL, and will modify it according to various conditions.
I'm not sure what is the best practice to do this; for example, right now, under "Partner A" section, if the category is different than "premiuim", my final_url
variable will remain empty. I guess I can make a condition that will check if it's empty and in that case it should apply to it the value of $url3
, but it doesn't feel smart enough:
<?php
$url = "http://www.default.com"; // default URL
$url = "something"; // this part will come from a database
$id="something"; // some value to insert later into URL
// the following rules will be followed according to various parameters not defined in this sample code
if($partner == "A") { // Partner A rule:
$url2 = str_replace('777', '999', $url); // Inital Change
$url3 = str_replace('?location', '?id=' . $id . '&location', $url2); // Add id, anytime ?location shows up
if($category == "premium") { // premium category rules:
$re = "/(?<=TID%3D)\\d+/"; // String to Replace in URL (digits)
$newtid = "4000"; // Default New TID
if($special == "yes") { $newtid = "8000";} // special TID value
$final_url = preg_replace($re, $newtid, $url3); // replace the TID
}
};
if($partner == "B") { // Partner B rule:
$final_url = str_replace('status=1', 'config=' . $id . '&status=1', $url); //Add id, anytime status=1 exists in url
};
?>
<p>Final URL: <?php echo $final_url; ?></p>
Also, I'm not sure that the whole structure is the optimal one, in general.
EDIT:
updated code:
if($category == 'A') {
// A category rules:
$url2 = str_replace('aaa', 'bbb', $url); // Global rule #1
$url3 = str_replace('?url', '?id=' . $id . '&url', $url2); // Glbal rule #2
$final_url = $url3; // Final URL unless following cases occur
if($offer == 'Special') {
//category is A and offer is special
$re = "/(?<=TID%3D)\\d+/"; // replace rule for current case
$tid = "123"; // Default New TID value for current case
$final_url = preg_replace($re, $tid, $url3); // Final URL for this case unless following case occur
if ($discount == '10') {
// category is A, offer is special, and Discount is 10
$re = "/(?<=TID%3D)\\d+/"; // replace rule for current case
$tid = "999"; // Special TID value for current case
$final_url = preg_replace($re, $itd, $url3); // Final URL for this case
}
}
}