Home >Backend Development >PHP Tutorial >Analysis of problems caused by the use of php trim method
This article brings you an analysis of the problems caused by the use of the php trim method. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Scenario
The characters before and after intercepting the string in php include three methods: ltrim, rtrim, and trim.
In the following example, only the ltrim method is used as an example
In my previous understanding (of course I am very ignorant and have never seen this source code), if I want to delete empty strings, empty tabs, etc. on the left side of the string, then I will use ltrim directly. ($str)
If I want to delete specified characters, for example, there is a string helloworld now, and I want to intercept the h character at the head, directly var_dump(ltrim("helloworld", " h")); can get the result I expected and output elloworld
The above are all within the range I thought, and I have always used it this way, until one time we had a need to print on some strings Do openssl_encrypt encryption. After encryption, make a base64, and then splice it with our special string prefix KO:. After each encryption is completed, splice the KO: character. Similarly, before decryption, remove the KO: first and then decrypt it. The result is that the decryption result is No matter how I solved it, it failed. Later, I made a few breakpoints and found that the result was different from the expected result when ltrim was used.
Recurrence
<?php // 以下做一个简单的情景复现 $str = "abccabdefg"; $character_mask = “abc”; var_dump(ltrim($str, $character_mask)); // 输出结果为 bdefg,而不是只截取前三位的abc
Cause analysis
After the above small steps demo, you should know the reason. The simplest and most popular way is that it performs a rotation training on the previous $str, character by character, and checks whether it is included in the subsequent $character_mask. If so, proceed. Intercept, stop running if it is not there
Expression in the form of ltrim code:
<?php $str = "abcccabdecbag"; $res = ''; $character_mask = 'abc'; $arrStr = str_split($str); // 字符串转数组 for ($i=0; $i<=count($arrStr); $i++) { if(strpos($character_mask, $arrStr[$i]) !== false) { unset($arrStr[$i]); } else { break; } } echo ltrim($str, $character_mask); echo "\r\n"; echo implode($arrStr); echo "\r\n";
Solution
The solution is to use some string manipulation functions in php, adding more basic judgments
if (substr($str, 0, strlen($character_mask)) == $character_mask) { echo substr($str, strlen($character_mask)); }
The above is the detailed content of Analysis of problems caused by the use of php trim method. For more information, please follow other related articles on the PHP Chinese website!