Reputation: 9305
I am trying to remove some parameters from a URL using PHP preg_replace(). For example, i need to remove a[]=1
from the bellow URL.
$my_url = 'www.myhost.com/filter.php?a[]=1&a[]=12&a[]=13&a[]=14'
So i am using:
$without_filter = preg_replace("/(&)?a\[\]=1/", '', $my_url);
I want to remove only a[]=1
, but it is removing the portion that contains a[]=1
from the others parameters, so am i getting:
www.myhost.com/filter.php?234
Someone can help me to solve this?
Upvotes: 0
Views: 115
Reputation: 4563
Following the man page of preg_replace you may do something like this:
$without_filter = preg_replace("/\&(a\[\]=1)(\&|$)/", '\2', $my_url);
Or... you can always use preg_replace_callback
Upvotes: 1
Reputation: 116
Use the $limit
parameter of preg_replace
and set it to 1
, this should replace it only once. Assuming that your parameters are always sorted this way:
$without_filter = preg_replace("/(&)?a\[\]=1/", '', $my_url, 1);
Upvotes: 0
Reputation: 5896
What about: /a\[\]=1(&|\b)/
That way it will capture a[]=1
only if it is followed by a &
or end of string.
Upvotes: 3