Marcio Mazzucato
Marcio Mazzucato

Reputation: 9305

How to define a exactly match using PHP preg_replace()

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

Answers (3)

songyy
songyy

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

kirmandi
kirmandi

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

Supericy
Supericy

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

Related Questions