0

I've just tested the following code:

echo ltrim('1-120', "1-");

I would expect this to echo out 120 however the output is 20. Rather than 120 that I would expect.

Like wise if I run echo ltrim('1-11120', "1-"); then 20 is still the output. Rather than 1120.

I have updated my code to use str_replace. So my question is more to improve my understanding why I am getting this output.

From looking on https://www.php.net/manual/en/function.ltrim.php The - is not listed in the charter section. Is this possibly a bug?

  • 2
    No, what this does is say "remove any of the following chars from the left". In your case, it's the same as saying "use a list of ['1', '-'] and from the left, take them **ALL** out in no particular order". It's not "this exact string", it's "any of these chars" - so any one or dash is removed from the left until it doesn't find either of those – Can O' Spam Aug 26 '22 at 13:29
  • 1
    Using `str_replace` may eventually have unintended side-effects, ie. if the leading substring appears elsewhere in the string, all instances will be removed. You can `preg_replace('~^1-~', '', $str)` to anchor the substring to match only at the start of a string. – Markus AO Aug 26 '22 at 14:11
  • Good point @Markus AO Will keep this in mind – Jason Bruce-Halliwell Aug 26 '22 at 15:09

0 Answers0