preg_quote函数允许指定要转义的附加分隔符。但是为了替换的目的,是否也可以指定分隔符而不是来转义呢?
例如,我希望转义所有东西(包括附加分隔符"/"),但"*"和"\"除外。
有点像:
$str = 'Replace/this line $15 #1 except \w* {';
$str = preg_quote_except($str, '/', '\*');
// Should be identical to:
$str = 'Replace\/this line \$15 \#1 except \w* \{';更新
虽然我很感谢您在被请求的几秒钟后将此标记为一个复制,但它实际上不是How to escape only certain characters的副本。那里的用户只想要特定的字符,而我只想要,除了一些。我不想手动管理要转义的内容(BTW,记住PHP偶尔添加新字符来转义)。
发布于 2019-03-08 21:48:29
你可以撤销不想要的逃跑。
$str = preg_quote($str, '/');
$str = str_replace(['\\*', '\\\\'], ['*', '\\'], $str);这可以是一个功能:
function preg_quote_except($str, $except, $delim = NULL) {
$str = preg_quote($str, $delim);
for ($i = 0; $i < strlen($except); $i++) {
$from[] = '\\' . $except[$i];
$to[] = $except[$i];
}
return str_replace($from, $to, $str);
}然后你就会说:
$str = preg_quote_except($str, '\\*', '/');我将分隔符参数移到末尾,以便它可以是可选的。
https://stackoverflow.com/questions/55071216
复制相似问题