JavaScript Editor Ajax software     Free javascripts 



Main Page

The good thing with associative arrays, and the reason for which it’s sometimes worth using them, is
that they’re easy to manipulate. Now that you have the query string broken into an associative array,
you only need to
unset()
the parameter you want to remove. In this case,
$param
will be
‘aff_id’
:
// remove the $param element from the array
unset($qs_array[$param]);
You now have an associative array that contains the elements you need in the new query string, so you
join these elements back in a string formatted like a query string. Note that you only do this if the asso-
ciative array is not empty, and that you use the ternary operator to compose the query string:
// create the new query string by joining the remaining parameters
$new_query_string = ‘’;
if ($qs_array)
{
foreach ($qs_array as $name => $value)
{
$new_query_string .= ($new_query_string == ‘’ ? ‘?’ : ‘&‘)
. urlencode($name) . ‘=’ . urlencode($value);
}
}
As soon as the new query string is composed, you join in back with the URL path you initially stripped
(which in this case is
/aff_test.php
), and return it:
// return the URL that doesn’t contain $param
return $url_path . $new_query_string;
}
We hope this has proven to be an interesting string handling exercise. For those of you in love with regu-
lar expressions, we’re sure you may guess they can be successfully used to strip the
aff_id
parameter
from the query string. Here it is if you’re curious:
function remove_query_param($url, $param)
{
// remove $param
$new_url = preg_replace(“#aff_id=?(.*?(&|$))?#“, ‘’, $url);
// remove ending ? or &, in case it exists
if (substr($new_url, -1) == ‘?’ || substr($new_url, -1) == ‘&‘)
{
$new_url = substr($new_url, 0, strlen($new_url) - 1);
}
What about the ternary operator? If you aren’t familiar with it, here’s a quick expla-
nation. The ternary operator has the form
(condition ? valueA : valueB)
. In
case the condition is true, it returns
valueA
, otherwise it returns
valueB
.
In your case, you verify if
$new_query_string
is empty; if this is true, then you first
add the
?
character to it, which is the delimiter for the first query string parameter.
For all the subsequent parameters you use the
&
character.
117
Chapter 5: Duplicate Content
c05.qxd:c05 10:41 117


JavaScript Editor Ajax software     Free javascripts 
this post