views:

93

answers:

4

Masters of regular expressions, please help!

See this string:

$string = "http://www.url.com/?fieldA=123&fieldB=456&fieldC=789";

Assuming "fieldB" always has a positive non-decimal numerical value (but not necessarily three digits long), what preg_replace command do I need to remove it completely, such that the string will then read:

$string = "http://www.url.com/?fieldA=123&fieldC=789";

Thanks!

+2  A: 
$string = preg_replace('/&?fieldB=[0-9]+/', '', $string);
Chad Birch
@Chad Birch, isn't `\d` faster than `[0-9]`?
macek
It might be, or it might be slower, depending how it's handled. Either way, that's the kind of optimization that I see on the level of "aren't single quotes faster than double quotes?" It's not really worth worrying about, I just find `[0-9]` easier to read.
Chad Birch
This will fail if fieldB is the first parameter.
MadCoder
Fair enough, changed it so that it will work now either way.
Chad Birch
A: 
$string = preg_replce('/fieldB=([0-9]+)/', '', $string);
bigstylee
typo, removed :)
bigstylee
Chad Birch
+1  A: 

Try this:

$string = preg_replace('/&fieldB=[0-9]+/', '', $string);

Working example code:

$string = "http://www.url.com/?fieldA=123&fieldB=456&fieldC=789";
$string = preg_replace('/&fieldB=[0-9]+/', '', $string);
echo $string;

//gives http://www.url.com/?fieldA=123&fieldC=789
zombat
@zombat, this looks pretty similar to an answer that was clearly posted before yours.
macek
When I posted mine, the other ones in the thread all contained incorrect code.
zombat
A: 

With preg_replace():

$url = preg_replace('!&?fieldB=\d+!', '', $string);

You should remove the & before it as well. Also, don't use [0-9]. Use \d instead.

That being said, PHP has good native functions for manipulating URLs. Another way to do this:

$url = parse_url($string);
parse_str($url['query'], $query);
unset($query['fieldB']);
$url['query'] = http_build_query($query);
$string = http_build_url($url);

Note: Unfortunately, the HTTP extension is not a standard extension so you have to install it.

cletus