仅修剪字符串中字符的第一个和最后一个出现位置 (PHP)
这是我可以一起破解的东西,但我想知道是否有人对我的问题有一个干净的解决方案。我拼凑起来的东西不一定非常简洁或快速!
我有一个像这样的字符串 ///hello/world///
。我只需要删除第一个和最后一个斜杠,而不是其他斜杠,这样我就得到像这样的字符串 //hello/world//
。
PHP 的 trim
不太正确:执行 trim($string, '/')
将返回 hello/world
。
需要注意的一件事是,字符串的开头或结尾不一定有任何斜杠。以下是我希望对不同字符串发生的情况的一些示例:
///hello/world/// > //hello/world//
/hello/world/// > hello/world//
hello/world/ > hello/world
提前感谢您的帮助!
This is something I could hack together, but I wondered if anybody had a clean solution to my problem. Something that I throw together wont necessarily be very concise or speedy!
I have a string like this ///hello/world///
. I need to strip only the first and last slash, none of the others, so that I get a string like this //hello/world//
.
PHP's trim
isn't quite right right: performing trim($string, '/')
will return hello/world
.
One thing to note is that the string won't necessarily have any slashes at the beginning or end. Here are a few examples of what I would like to happen to different strings:
///hello/world/// > //hello/world//
/hello/world/// > hello/world//
hello/world/ > hello/world
Thanks in advance for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我首先想到的是:
First thing on my mind:
该函数的作用与官方修剪相同,只不过它只修剪一次。
This function acts as the official trim, except that it only trims once.
这是迄今为止最简单的一个。它匹配 ^/(开始斜杠)和 /$(结束斜杠),如果找到其中一个,则将其替换为空字符串。这适用于任何角色;只需将以下正则表达式中的 / 替换为您选择的字符即可。请注意,分隔符我使用 # 而不是 / 以使其更易于阅读。这将从字符串中删除任何单个第一个或最后一个 /:
结果:
This one is by far the simplest. It matches on ^/ (start slash) and /$ (end slash) and if either are found it is replaced with an empty string. This will work with any character; just replace / in the following regular expression with the character of your choice. Note for the delimiter character I used # instead of / to make it easier to read. This will remove any single first or last / from a string:
Results:
我认为这就是您正在寻找的:
I think this is what you you are looking for:
使用反向引用的不同正则表达式:
这样做的优点是,如果您想使用除 / 之外的字符,您可以更清晰地这样做。它还强制 / 字符作为字符串的开头和结尾,并允许 / 出现在字符串中。最后,如果末尾也有字符,它只会从开头删除该字符,反之亦然。
A different regex, using backreferences:
This has the advantage that, should you want to use characters other than /, you could do so more legibly. It also forces the / character to begin and end the string, and allows / to appear within the string. Finally, it only removes the character from the beginning if there is a character at the end as well, and vice versa.
还有一个实现:
Yet another implementation:
已经有六年多了,但我还是给出可能的答案:
It has been more than 6 years old ago, but I'm giving may answer anyway:
我写了这段代码来修剪一次字符
I wrote this code for trim once characters