3 回答

TA貢獻1860條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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 關注
- 227 瀏覽
添加回答
舉報