0

Fairly new to PHP and trying to figure out something that I can't get my head around too.

I have a URL below where I want to remove &page_number=x. The page_number variable and the number has to be removed with the function, which will always be at the end of the string.

http://url.com/search/?location=london&page_number=1

I have tried a few versions of preg_replace but I am not having any luck.

Thanks

Cam
  • 137
  • 1
  • 2
  • 10

4 Answers4

1
&page_numer=\d+$

Try this.Replace by empty string.

See demo.

https://regex101.com/r/gX5qF3/10

vks
  • 67,027
  • 10
  • 91
  • 124
1

If its the current page it can be done like this:

 unset($_GET['page_number']);
 $newStr='?'.http_build_query($_GET); 
andrew
  • 9,313
  • 7
  • 30
  • 61
1
$str = 'http://url.com/search/?location=london&page_number=1';
$str = preg_replace('/[?&]page_number=\d+/', '', $str);
Zaffy
  • 16,801
  • 8
  • 50
  • 77
Dmitri Kadykov
  • 505
  • 2
  • 6
  • Hi thank you for this brilliant solution. I love regular expressions and this does exactly what it needs to. Happy New Year may it bring great fortunes for you :) – Cam Dec 29 '14 at 13:41
  • Thank you for your wish :) And thanks @Zaffy for correct editing – Dmitri Kadykov Dec 29 '14 at 13:43
0

The following code should remove it without regex's or expensive explode:

$str = 'http://url.com/search/?location=london&page_number=1';
$cropped = substr($str, 0, strrpos($str, '&page_number='));
// $cropped is 'http://url.com/search/?location=london'

First, it looks for position of last occurance of &page_number= using strrpos, then crops the string up to that occurance using substr.

Note: This assumes that the parameter that you want to remove is at the end.

Sebi
  • 1,390
  • 1
  • 13
  • 22
  • Can the downvoter please provide me some feedback on what's wrong with my answer? – Sebi Dec 29 '14 at 13:28
  • Hi thank you for the solution. I have tried it and it works also. Much appreciated for your time. – Cam Dec 29 '14 at 13:40