3 回答
TA贡献1860条经验 获得超9个赞
如果您使用的是正则表达式,则必须price专门捕获并将分隔符的前后部分捕获%2C到单独的正则表达式组中并替换它们。它看起来像下面这样:
preg_replace('/(price\=)([^&]*)%2C[^&]*/', '$1$2', $str)'
-------- ------- ----
Grp 1. Grp 2. Only grp 1 and 2.
片段:
<?php
$tests = [
'test.xyz/builder-list/?price=301-500%2C501-1000&builder_country=6442%2C6780%2C6441',
'test.xyz/builder-list/?price=-200%2C400-500&builder_region=1223%2C3445',
'test.xyz/builder-list/?builder_state=45%2C76&price=-200%2C400-500',
'test.xyz/builder-list/?builder_state=45%2C76&price=%2C400-500'
];
foreach($tests as $test){
echo preg_replace('/(price\=)([^&]*)%2C[^&]*/', '$1$2', $test),PHP_EOL;
}
演示: http://sandbox.onlinephpfunctions.com/code/f5fd3acba848bc4f2638ea89a44c493951822b80
TA贡献2036条经验 获得超8个赞
$string = 'test.xyz/builder-list/?builder_state=45%2C76&price=-200%2C400-500';
//Separate string based on & an make an array $q
$q = explode('&', $string);
//Go through each item in array $q and make adjustments
//if it's the price-query
foreach($q as &$item) {
if (stristr($item,'price') !== false) {
//Just leave left the first part of
//this item before %2C
$pos = strpos($item, '%2C');
$item = substr($item,0,$pos);
break; //No need being here in this loop anymore
}
}
//Implode back to original state and glue it together with ampersand
$result = implode('&', $q);
$result将包含:
test.xyz/builder-list/?builder_state=45%2C76&price=-200
TA贡献1921条经验 获得超9个赞
正则表达式的另一种选择是通过parse_str.
使用第一个strtok获取基本 url 并将其分开,以便您可以在parse_str.
在将其分离并加载到 中之后parse_str,您可以对查询字符串的各个部分进行更改。如果您想更改价格,请像这样操纵它。
使用另一个只是为了有效地修剪or ( )strtok之后的字符并重新分配。,%2C
http_build_query最后,使用之前操作中分离的基本 url 连接的方式重新附加查询字符串。
$string = 'test.xyz/builder-list/?price=-200%2C400-500&builder_region=1223%2C3445';
$base_url = strtok($string, '?');
parse_str(str_replace("{$base_url}?", '', $string), $data);
$data['price'] = strtok($data['price'], ',');
$final_string = "{$base_url}?" . http_build_query($data);
echo $final_string;
- 3 回答
- 0 关注
- 186 浏览
添加回答
举报