Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

trim

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?

like image 225
sica07 Avatar asked May 04 '18 11:05

sica07


People also ask

How do I remove the first character of a string?

To delete the first character from a string, you can use either the REPLACE function or a combination of RIGHT and LEN functions. Here, we simply take 1 character from the first position and replace it with an empty string ("").

How do I remove a character from a string?

We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.


2 Answers

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.

like image 55
Cid Avatar answered Oct 22 '22 04:10

Cid


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.
like image 27
Sergei Karpov Avatar answered Oct 22 '22 04:10

Sergei Karpov