PHP Removing part of a dynamic string

Associate
Joined
26 Jun 2003
Posts
1,140
Location
North West
I have strings like this (URL):

?p1=users&p2=management&orderby=dateregistered&order=DESC&p=2

or

?p1=users&p2=management&p=2&orderby=dateregistered&order=DESC

How would I elimate certain variables from this? such as p?

I need to remove &p=2 (the number can be any number).

How can this be done?
 
Well this is the kind of thing i need to do

Code:
$string = $_SESSION['QUERY_STRING'];

$string = removeP($string);

echo '<a href="'.$string.'">Link</a>'
 
Last edited:
There's probably a way of going through the string until it finds "p=" and it then removes that bit plus one character.

Would be easier though to remove it from the url. Isn't there any way of not sending it through the url?
 
Code:
$fullstring = $_SESSION['QUERY_STRING'];

$position = stripos($fullstring, '&p2='); //finds position of the & in '&p2='

$firstbit = strstr($fullstring, 0, $position); //gives up to the &
$remainder = strstr($fullstring, $position); //gives the rest, including '&p2='

$position2 = stripos($lastbit, '&', 1); //gives the position of the next part

$lastbit = strstr($remainder, $position2); //last bit including &

$newstring = $firstbit . $lastbit; //complete string

Untested, might work :)
 
Dj_Jestar said:
Code:
$string = preg_replace('/' . preg_quote('&p=', '/') . '\d+/', '', $string);

untested.

That works fine at the moment, cant see any bugs. Im not sure what that preg_quote is doing tho.
 
Dj_Jestar said:
Code:
$string = preg_replace('/' . preg_quote('&p=', '/') . '\d+/', '', $string);

untested.
Not sure. Looks like it would only replace '&p=' with ''.

What does the \d+/ do? All those slashes are confusing.
 
Last edited:
Oh I see, you want to get rid of p. As in &p=2.

:( Dammit, thought you wanted &p2=...

Much harder, as its variable length, so you have to chop it up before the & and before the next &, removing that piece.
 
joeyjojo said:
Not sure. Looks like it would only replace '&p=' with ''.

What does the \d+/ do? All those slashes are confusing.

Yeh whats is that d+?

What what I have to change if instead of numbers after the p there was letters?
 
JonD said:
What what I have to change if instead of numbers after the p there was letters?
I think it replaces the &d= (edit: thats a p) and the next character with blankness. As long as it's one char it's fine. For a variable number give my less classy thing a go.

Sorry about posting hundreds of times up there :o :)
 
Last edited:
\d is the key word for Digits (numbers)

The + indicates there will be one or more occurances. Perhaps changing the pattern to:

Code:
&p=[^&]+
would be better suited as the value could literally be anything the user wishes.

I used preg_quote because I couldn't remember if & is a special char in PCRE :p

preg_quote simply escapes all special characters in a pattern string.
 
Last edited:
Back
Top Bottom