php - 从 PHP 中特定字符串的开头删除字符串
问题描述
我在 php 中有一个这样的 url 字符串:
$string = 'test.xyz/builder-list/?price=301-500%2C501-1000&builder_country=6442%2C6780%2C6441';
我想从price
以 `%2c. 开头的 URL 字符串中的查询值中删除特定字符串。例如:
test.xyz/builder-list/?price=301-500%2C501-1000&builder_country=6442%2C6780%2C6441
into
test.xyz/builder-list/?price=301-500&builder_country=6442%2C6780%2C6441
test.xyz/builder-list/?price=-200%2C400-500&builder_region=1223%2C3445
into
test.xyz/builder-list/?price=-200&builder_region=12%2C33
test.xyz/builder-list/?builder_state=45%2C76&price=-200%2C400-500
into
test.xyz/builder-list/?builder_state=45%2C76&price=-200
我尝试使用此preg_replace
功能,但它删除了所有%2C
字符串
preg_replace('/' . preg_quote('%2C') . '.*?/', '', $string);
解决方案
如果您使用的是正则表达式,则必须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
推荐阅读
- installation - 离线安装 k3s
- php - 将数据放入 php 文件中
- javascript - 当用户点击一个按钮时,需要同时调用一个 JavaScript 函数和一个代码隐藏函数
- iphone - Django no referer CSRF 错误仅在 iPhone 上
- ecmascript-6 - Stripe - ReferenceError:未定义要求
- azure - 从静态文件 SPA 调用 Azure Function App
- python - 我正在尝试编写一个 Pig Latin 翻译器,它可以接收整个句子并翻译每个单词
- python - 将安装的 CPLEX 导入 Anaconda
- c# - 在没有焦点的控制台应用程序上记录空间
- angular - 使用 Charles-Proxy 错误状态重写是 -1 而不是 503