Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex Help 1

Status
Not open for further replies.

SPYDERIX

Technical User
Jan 11, 2002
1,899
CA
Hi,

I suck at regex and need a bit of help. I need to take the query string from a page and do a search and replace on the page variable so I can re-write it.

Assume this:
query string = ?search=whatever&page=5

I need the rule to be like this:
Find page= which is then followed by any number of [0-9] keeping in mind that it might be blank or followed by another get variable after it (in which case stop before the & sign).

I have this (basic as if the page variable is at the end of the query string):

$new_q = preg_replace ("page=[0-9]+", "page=" . $new_page, $_SERVER["QUERY_STRING"]);

It doesn't work though. What am I doing wrong? Any thoughts?

Thanks alot.



NATE


mainframe.gif


Got a question? Search G O O G L E first.
 
i've never got my head around the regex languages either. i've always found regex quite slow too. so my natural inclination is to code around the need.

the code below should do what you need (and might be faster!)
Code:
<?
$vars = $_SERVER['QUERY_STRING'];

$vars_array = explode ("&",$vars); //chunks into an array based on the var separator
foreach ($vars_array as $key=>$value)
{
  $newvar = explode("=", $value); //we now have an array whose key = varname and val = value
  $query_array[$newvar[0]] = $newvar[1]; 
}
unset ($vars_array); //clean up
unset ($vars); //clean up

// now if you want to rewrite the page var
$query_array['page'] = "new value";
?>
 
Ahhhhhhhhhhhh

I got it. I was close:

$new_q = preg_replace ("'page=[0-9]+'", "page=" . $new_page, $_SERVER["QUERY_STRING"]);

NATE


mainframe.gif


Got a question? Search G O O G L E first.
 
well, i just want to improve on that:

$new_q = preg_replace ("'page=[0-9]*'", "page=" . $new_page, $_SERVER["QUERY_STRING"]);

make it *, this way the number can or cannot be there...

Known is handfull, Unknown is worldfull
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top