转义文件名斜杠
我想从用户输入的字符串生成文件名并确保它被安全转义。
例如,如果用户输入 /usr/bash
则输出将为 \/usr\/bash
如果输入是The Great Theater
,则输出是The\ Great\ Theater
。
I want to generate filename from a user-inputed string and to make sure that it is safely escaped.
for example, if the user enters /usr/bash
the output will be \/usr\/bash
and if the input is The great theater
the output is The\ great\ theater
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您确定需要这样做吗?这是一种代码味道。很可能有一种比破坏你的输入更好的方法来完成你想做的事情。使用变量时正确引用它们通常就足够了:
不过,如果您坚持,请在 printf 中使用
%q
格式:请注意,这不会转义斜杠,因为斜杠通常不是特殊字符。
Are you sure you need to do this? This is kind of a code smell. There's very likely a better way to do whatever you're trying to do than mangling your input. Properly quoting your variables when you use them usually suffices:
If you insist, though, use the
%q
format with printf:Note that this won't escape slashes as they aren't normally special characters.