我正在寻找一种从字符串中删除字符的方法,并且只删除指定字符后面的后两个字符。
我在这里找到了删除指定字符及其后的所有内容的方法,但我不认为substr函数可以满足我的需要。
$variable = substr($variable, 0, strpos($variable, "By"));
例如,我有一个包含此内容的字符串:
/path/shop.php?category=ab&page=xy
指定?category=
将删除?category=
和ab
。
不使用str_replace(因为我无法指定ab
)。
答案 0 :(得分:1)
使用preg_replace
和preg_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}
- 指向指定搜索子字符串
答案 1 :(得分:0)
只需获得2个子字符串:
$position = strpos($fullString, $removable);
$sub1 = substr($fullstring, 0, $position);
$sub2 = substr($fullstring,
$position + strlen($removable),
strlen($fullstring) -($position + strlen($removable)));
$finalString = $sub1 + $sub2;