PHP函数记录-trim导致的编码异常
生活随笔
收集整理的這篇文章主要介紹了
PHP函数记录-trim导致的编码异常
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近寫業務接口報500,排查發現是編碼問題導致 laravel response異常。
起初以為是DB編碼導致,排除后發現了是代碼中的trim導致的
//給到前端純潔的數據 之前有拼接¥%等標識 public function normalField($data) {$charlist = '%¥';foreach ($data as $tag => &$item) {array_walk_recursive($item, function (&$value) use ($charlist) {if (is_scalar($value)) {$value = trim($value, $charlist);}});break;}官方文檔
trim不是多字節的,比如中文相關的 utf8大部分是三個字節
這里用到了 ¥ 和字符串 包含了運營
即 trim(’運營’, ‘%¥’)
發現問題 尾字節 都是a5 trim會把誤傷 營的a5
¥對應的三個字節是 ef bf a5 營 對應的三個字節是 e8 90 a5文檔有提示作用機制
Note: Possible gotcha: removing middle characters Because trim() trims characters from the beginning and end of a string, it may be confusing when characters are (or are not) removed from the middle. trim('abc', 'bad') removes both 'a' and 'b' because it trims 'a' thus moving 'b' to the beginning to also be trimmed. So, this is why it "works" whereas trim('abc', 'b') seemingly does not.解決方式
參考
PHP字符串與字節轉換示例
PHP trim亂碼原因
總結
以上是生活随笔為你收集整理的PHP函数记录-trim导致的编码异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 今天在当当上看到一本书,ASP.NET程
- 下一篇: 知识图谱入门