[英]Why is PHP changing the first character after ltrim or str_replace?
我正在尝试使用PHP ltrim()删除目录的一部分,但是结果出乎意料。 我的结果的第一个字母具有错误的ascii值,并在浏览器中显示为缺少的字符/框。
这是我的代码:
$stripPath = "public\docroot\4300-4399\computer-system-upgrade";
$directory = "public\docroot\4300-4399\computer-system-upgrade\3.0 Outgoing Documents";
$shortpath = ltrim($directory, $stripPath);
echo $shortpath;
预期产量:
3.0 Outgoing Documents
实际输出:
.0 Outgoing Documents
注意点之前的不可见/非打印字符。 ASCII值从十六进制33(数字3)更改为十六进制03(不可见字符)。 我还尝试了str_replace()而不是trim(),但是结果保持不变。
我在这里做错了什么? 我如何获得预期的结果“ 3.0外发文档”?
当您在引号中提供字符串值时,必须注意反斜杠用作屏蔽字符。 因此, \\3
被理解为ASCII(3)字符。 在您的示例中,您需要提供双反斜杠以定义所需的字符串(其中包含单个反斜杠):
$stripPath = "public\\docroot\\4300-4399\\computer-system-upgrade\\";
$directory = "public\\docroot\\4300-4399\\computer-system-upgrade\\3.0 Outgoing Documents";
反斜杠是PHP的转义序列。 在'stripPath'中添加反斜杠以将其从'dirctory'中修剪
不要使用ltrim。
Ltrim不直接替换。 它像正则表达式一样剥离。
意思是您在第二个参数中输入的所有字符都用于删除任何内容。
查看范例: https : //3v4l.org/AfsHJ
停止的原因.
是因为它不属于$stripPath
相反,您应该使用真正的正则表达式或简单的str_replace。
$stripPath = "public\docroot\4300-4399\computer-system-upgrade";
$directory = "public\docroot\4300-4399\computer-system-upgrade\3.0 Outgoing Documents";
$shortpath = str_replace($stripPath, "", $directory);
echo $shortpath;
发生这种情况是因为/
标记,因为/
具有特殊含义。
如果您尝试使用空格 您可以获得预期的输出。
$stripPath = "public\docroot\4300-4399\computer-system-upgrade";
$directory = "public\docroot\4300-4399\computer-system-upgrade 3.0 Outgoing Documents";
$shortpath = ltrim($directory, $stripPath);
echo $shortpath;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.