php - 仅修剪字符串中第一次和最后一次出现的字符 (PHP)

标签 php string trim

这是我可以破解的东西,但我想知道是否有人对我的问题有一个干净的解决方案。我拼凑的东西不一定非常简洁或快速!

我有一个像这样的字符串 ///hello/world///。我只需要去掉第一个和最后一个斜线,其他的都不需要,这样我就得到了这样的字符串 //hello/world//

PHP 的 trim 不太正确:执行 trim($string, '/') 将返回 hello/world

需要注意的是字符串的开头或结尾不一定有任何斜线。以下是我希望对不同字符串进行处理的几个示例:

///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 - 仅修剪字符串中第一次和最后一次出现的字符 (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3834319/

相关文章:

python - 动态拆分Python中的复杂字符串

php - Laravel 5 邮件队列不工作

php - 有人可以解释如何在将 html 输入值写入 .txt 文件的 php 脚本之后重定向 url

php - 使用php编辑sql表数据

java - 将 "\"更改为 "/"

ruby - 在 Ruby 中构建长字符串的简洁方法

C# - 更改小数位数

c# - 如何修剪字节数组的几个字节?

PHP 修剪和空间不起作用

php - 将头标签信息存储在单独的文件中并稍后包含它是一个好习惯吗?