删除某个字符后的一定数量的字符

Remove a certain number of characters after a certain character

我正在寻找一种方法来从字符串中删除一个字符,并仅删除指定字符之后的下两个字符。

我在这里找到了删除指定字符及其后所有内容的方法,但我认为 substr 函数无法满足我的需要。

$variable = substr($variable, 0, strpos($variable, "By"));

例如,我有一个包含以下内容的字符串:

/path/shop.php?category=ab&page=xy

指定 ?category= 将删除 ?category=ab

没有使用str_replace(因为我不能指定ab)。

使用preg_replacepreg_quote函数的解决方案:

$str = '/path/shop.php?category=ab&page=xy';
$v = '?category=';
$result = preg_replace("/". preg_quote($v) .".{2}/", "", $str);

print_r($result);

输出:

/path/shop.php&page=xy

.{2} - 指向指定搜索子字符串后的下 2 个字符

只得到2个子串:

$position = strpos($fullString, $removable);
$sub1 = substr($fullstring, 0, $position);
$sub2 = substr($fullstring, 
$position + strlen($removable), 
strlen($fullstring) -($position + strlen($removable)));

$finalString = $sub1 + $sub2;