仅当不属于另一个子字符串的一部分时才删除子字符串
Remove a substring only if not part of another substring
我正在尝试从字符串中删除一个子字符串,但前提是该子字符串不属于另一个更大的子字符串。我希望这已经足够清楚了。
例如,我想从下面的字符串中删除所有出现的字母 'p',但前提是它后面没有跟 'e'。换句话说,我想删除 'p',但如果 'pe'.
apes are super people
应该变成:
apes are super peole
如您所见,只删除了一次出现的字母 'p'。
您可以使用这个否定的先行正则表达式:
/p(?!e)/
p(?!e)
表示匹配 p
如果后面没有字母 e
.
代码:
$re = "/p(?!e)/";
$str = "apes are super people";
$result = preg_replace($re, '', $str);
//=> apes are super peole
您可以使用带有 negative lookahead, to make sure no 'e' follows 'p', then you can use the regex with preg_replace()
:
的正则表达式
preg_replace("/p(?!e)/", "", $string);
我正在尝试从字符串中删除一个子字符串,但前提是该子字符串不属于另一个更大的子字符串。我希望这已经足够清楚了。
例如,我想从下面的字符串中删除所有出现的字母 'p',但前提是它后面没有跟 'e'。换句话说,我想删除 'p',但如果 'pe'.
apes are super people
应该变成:
apes are super peole
如您所见,只删除了一次出现的字母 'p'。
您可以使用这个否定的先行正则表达式:
/p(?!e)/
p(?!e)
表示匹配 p
如果后面没有字母 e
.
代码:
$re = "/p(?!e)/";
$str = "apes are super people";
$result = preg_replace($re, '', $str);
//=> apes are super peole
您可以使用带有 negative lookahead, to make sure no 'e' follows 'p', then you can use the regex with preg_replace()
:
preg_replace("/p(?!e)/", "", $string);