【问题标题】:Why is PHP changing the first character after ltrim or str_replace?为什么 PHP 更改 ltrim 或 str_replace 之后的第一个字符?
【发布时间】:2018-06-15 04:04:45
【问题描述】:

我正在尝试使用 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 值从 Hex 33(数字 3)更改为 Hex 03(不可见字符)。 我也尝试了 str_replace() 而不是 trim(),但结果保持不变。

我在这里做错了什么?我将如何获得预期的结果“3.0 Outgoing Documents”?

【问题讨论】:

    标签: php string str-replace trim


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的意见,但我认为还有更多。我将所有 \ 替换为 \\ 和 / 只是为了测试并确认这些值是在 xdebug 中设置的,但我仍然遇到同样的问题。让我感到困惑的是,它总是在以 3、4、6 或 9 开头的文件夹上中断,其他的都可以...?
    【解决方案2】:

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

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

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

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

      【讨论】:

        【解决方案4】:

        反斜杠是 PHP 的转义序列。向“stripPath”添加反斜杠以将其从“目录”中删除

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-04-29
          • 1970-01-01
          • 2018-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-21
          相关资源
          最近更新 更多