仅修剪字符串中字符的第一次和最后一次出现 (PHP) [英] Trim only the first and last occurrence of a character in a string (PHP)
问题描述
这是我可以一起破解的东西,但我想知道是否有人对我的问题有一个干净的解决方案.我拼凑起来的东西不一定非常简洁或快速!
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!
我有一个这样的字符串 ///hello/world///
.我只需要去掉第一个和最后一个斜杠,其他的都不要,这样我就得到一个这样的字符串 //hello/world//
.
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 的 trim
不太正确:执行 trim($string, '/')
将返回 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
在此先感谢您的帮助!
推荐答案
我想到的第一件事:
if ($string[0] == '/') $string = substr($string,1);
if ($string[strlen($string)-1] == '/') $string = substr($string,0,strlen($string)-1);
这篇关于仅修剪字符串中字符的第一次和最后一次出现 (PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!