PHP preg_replace URL field
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&fi开发者_Python百科eldC=789";
$string = preg_replace('/&?fieldB=[0-9]+/', '', $string);
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
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.
$string = preg_replce('/fieldB=([0-9]+)/', '', $string);
精彩评论