首页 > 解决方案 > 从 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);

标签: phpregexstring

解决方案


如果您使用的是正则表达式,则必须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


推荐阅读