Why does ltrim remove one character when the second argument contains an operator sign? [duplicate]

房东的猫 提交于 2019-12-08 15:24:36

问题


If I do:

ltrim('53-34567', '53-');
ltrim('53+34567', '53+');
ltrim('53*34567', '53*');

I get 4567 as the result and not 34567. What's the explanation for this behavior?


回答1:


ltrim('53-34567', '53-');

There is a 5 at the begining of '53-34567' so it is removed.

There is a 3 at the begining of '3-34567' so it is removed.

There is a - at the begining of '-34567' so it is removed.

There is a 3 at the begining of '34567' so it is removed.

There is nothing in '53-' at the begining of '4567' so it stopped.

This is the same behaviour than a trim() by removing unwanted trailing characters. In example, trim(" lots of spaces "); will return "lots of spaces" by removing trailing and leading spaces but will keep the inner ones.




回答2:


The second argument of ltrim() is as follows

character_mask
You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped.

It's used to specify which characters to trim, yours include 3. If you know what you want to extract, you can use other string functions.

As to why the other 5 is then not removed, see this comment: http://php.net/manual/en/function.ltrim.php#118221




回答3:


This is because ltrim trims characters from a second param.

How it works:

  1. start read a string(first param) from left.
  2. check if first-left char is in a list of 'character-to-trim' list.
  3. If 2 is YES - trim it and go to step 1.
  4. if 2 is NO - exit.


来源:https://stackoverflow.com/questions/50174181/why-does-ltrim-remove-one-character-when-the-second-argument-contains-an-operato

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!