[英]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.