dounuo8797 2018-06-15 04:04
浏览 117
已采纳

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

I'm trying to remove a part of a directory with PHPs ltrim(), however the result is unexpected. The first letter of my result has the wrong ascii value, and shows up as missing character/box in the browser.

Here is my code:

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

Expected output:

3.0 Outgoing Documents

Actual output:

.0 Outgoing Documents

Note the invisible/non-print character before the dot. Ascii value changed from Hex 33 (the number 3) to Hex 03 (invisible character). I also tried str_replace() instead of trim(), but the result stays the same.

What am i doing wrong here? How would i get the expected result "3.0 Outgoing Documents"?

  • 写回答

4条回答 默认 最新

  • dsjfrkvn818747 2018-06-15 07:21
    关注

    Don't use ltrim.
    Ltrim does not replace straight off. It strips kind of like regex does.
    Meaning all characters you put in the second argument is used to remove anything.
    See example: https://3v4l.org/AfsHJ
    The reason it stops at . is because it's not part of $stripPath

    You should instead do is use real regex or simple 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条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘