为什么PHP在ltrim或str_replace之后改变了第一个字符?

时间:2018-06-15 04:04:45

标签: php string str-replace trim

我试图用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外发文件"?

4 个答案:

答案 0 :(得分:3)

当您在引号中提供字符串值时,您必须知道反斜杠用作屏蔽字符。因此,\3被理解为ASCII(3)字符。在您的示例中,您需要提供双反斜杠以定义所需的字符串(其中包含单个反斜杠):

$stripPath = "public\\docroot\\4300-4399\\computer-system-upgrade\\";
$directory = "public\\docroot\\4300-4399\\computer-system-upgrade\\3.0 Outgoing Documents";

答案 1 :(得分:1)

反斜杠是PHP的转义序列。在'stripPath'中添加一个反斜杠以从'dirctory'

中修剪它

答案 2 :(得分:1)

不要使用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;

https://3v4l.org/KF2Iv

答案 3 :(得分:0)

这是因为/标记,因为/具有特殊含义。

如果您使用空格尝试此操作,则可以获得预期的输出。

$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;