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

为什么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"?

我正在尝试使用PHP ltrim()删除目录的一部分,但结果是意外的。 我的结果的第一个字母具有错误的ascii值,并在浏览器中显示为缺少字符/框。 p>

这是我的代码: p>

  $ stripPath =“public \ docroot \ 4300-4399 \ computer-system-upgrade”; \  n $ directory =“public \ docroot \ 4300-4399 \ computer-system-upgrade \ 3.0 Outgoing Documents”; 
 
 $ shortpath = ltrim($ directory,$ stripPath); 
echo $ shortpath; 
  code  >  pre> 
 
 

预期输出: p>

  3.0外发文件
  code>  pre> 
 
 

实际 输出: p>

  .0传出文件
  code>  pre> 
 
 

注意点之前的不可见/非打印字符。 Ascii值从十六进制33(数字3)变为十六进制03(不可见字符)。 我也尝试使用str_replace()而不是trim(),但结果保持不变。 p>

我在这做错了什么? 我如何得到预期的结果“3.0外发文件”? p> div>

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

That happens because of / mark because / has a special meaning.

If you try this with a space you can get the expected output.

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

When you provide a string value in quotation marks you have to be aware that the backslash is used as a masking character. So, \3 is understood as the ASCII(3) character. In your example you need to provide double backslashes in order to define your desired string (having single backslashes in it):

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

Backslash is PHP’s escape sequence. Add a backslash to ‘stripPath’ to trim it from ‘dirctory’